【问题标题】:Testing Associations with rspec and Factory Girl与 rspec 和 Factory Girl 的测试协会
【发布时间】:2015-07-16 20:49:51
【问题描述】:

我的模型;家庭 has_many :neighbors 和 Neighbor belongs_to :household

每个家庭必须有一个邻居:

   validates :neighbors, presence: {message: 'You must enter at least one neighbor']

我正在尝试创建一个工厂

   factory :household, class:  "Household" do
     household_name "Brooke"
     neighbor
   end


   factory :neighbor, class: "Neighbor" do
     first_name "Tom"
     last_name "Brooke"
   end 

    it "has a valid factory"  do
      household = create(:household, neighbors: :neighbor)
      expect(household).to be_valid
    end

这给了我:

  undefined method `neighbor=' for #<Household:0x007fd45ec85138>

如何成立Factory Girl来体现协会?

【问题讨论】:

  • 另一个任务!!!

标签: ruby-on-rails associations factory-bot


【解决方案1】:

我终于做到了:

我把邻居带出了家庭工厂:

  factory :household, class:  "Household" do
      household_name "Brooke"
    end

对于我的测试,我在测试中创建了关联:

   it "has a valid factory"  do
      neighbor = create(:neighbor)
      household = create(:household, neighbors: [neighbor])
      expect(household).to be_valid
   end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2011-08-27
    • 1970-01-01
    相关资源
    最近更新 更多