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

问题描述 投票:1回答:2

我有两个名为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

我在teacher中定义了student因为它们都有相同的属性,除了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工厂添加这些属性?

谢谢

ruby-on-rails rspec factory
2个回答
1
投票

如果你的StudentTeacher模型是2个不同的类而没有继承,你就无法做到你想要实现的目标。

根据FactoryBot source

您可以轻松地为同一个类创建多个工厂,而无需通过嵌套工厂重复公共属性

factory :post do
  title { "A title" }

  factory :approved_post do
    approved { true }
  end
end

如果Teacher继承了Student类,你实际上可以编写嵌套工厂。 示例:how to define factories with a inheritance user model


0
投票

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


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

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

这在同一家工厂创造了两个不同的工厂。 :)

© www.soinside.com 2019 - 2024. All rights reserved.