如何在 RSpec 的另一个工厂中定义一个工厂中的两个新属性?

How to define two new attributes in a factory which is defined inside another factory in RSpec?

我有两个模型,名为 StudentTeacher。它们都有相同的字段,如 nameage 等。除了 Teacher 有两个额外的属性 qualificationcollege。现在写 rspec,我决定创建如下相同的工厂:


FactoryGirl.define do
  factory :student do
    type 'student'

    factory :teacher do
      type 'teacher'
      qualification BA
      college XYZ
    end
  end
end

我在student里面定义了teacher,因为除了teacher有两个额外的属性外,它们都有相同的属性。我如上所述添加了属性,但它给出了错误:


  1) Teacher#default_value_for 
     Failure/Error: it { expect(subject.qualification).to be_false}

     NoMethodError:
       undefined method `qualification' for #Student:0x0000000e8c0088'

Finished in 1.75 seconds (files took 14.48 seconds to load)
1 example, 1 failure

如何在 Teacher 工厂中添加这些属性?

谢谢

如果您的 StudentTeacher 模型是 2 个不同的 classes 而没有继承,您将无法实现您想要实现的目标。

根据 FactoryBot source:

You can easily create multiple factories for the same class without repeating common attributes by nesting factories

factory :post do
  title { "A title" }

  factory :approved_post do
    approved { true }
  end
end

如果 Teacher 继承了 Student class.
,您实际上可以编写嵌套工厂 此处示例:如何使用继承用户模型定义工厂

我通过删除工厂中的嵌套解决了上述问题。


FactoryGirl.define do
  factory :student do
    type 'student'
  end

 factory :teacher do
   type 'teacher'
   qualification BA
   college XYZ
 end
end

这在同一个工厂中创建了两个不同的工厂。 :)