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

时间:2019-02-22 10:43:49

标签: ruby-on-rails rspec factory

我有两个名为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工厂中添加这些属性?

谢谢

2 个答案:

答案 0 :(得分:1)

如果您的@objc func playSound(sender: UIButton){ if soundPlayers.count >= 20 { soundPlayers.removeLast(10) } if let playingURL = Bundle.main.url(forResource: SoundFiles.shared.currentSoundfiles[sender.tag], withExtension: "wav"){ soundPlayers.append(Sound(url: playingURL)) soundPlayers[soundPlayers.count-1]?.volume = SoundFiles.shared.volume soundPlayers[soundPlayers.count-1]?.play() } } Student模型是2个没有继承的不同类,那么您将无法实现您想要的目标。

根据FactoryBot source

  

您可以轻松为同一课程创建多个工厂 ,而无需   通过嵌套工厂重复通用属性

Teacher

如果factory :post do title { "A title" } factory :approved_post do approved { true } end end 继承了Teacher类,您实际上可以编写嵌套工厂。
此处的示例:how to define factories with a inheritance user model

答案 1 :(得分:0)

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


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

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

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