FactoryGirl协会

时间:2013-12-20 17:43:24

标签: ruby-on-rails rspec ruby-on-rails-4 factory-bot

我有一个非常基本的rails应用程序,我正在努力。

部件处于某些状态(state_id),它们由用户(user_id)创建,并具有与之关联的类型(type_id)。

尝试为零件创建工厂,我有:

FactoryGirl.define do
  factory :part do
    name "blah"
    association :state_id, factory: :state
    association :user_id, factory: :user
    association :techtype_id, factory: :techtype
  end

  factory :state do
    name "blah"
  end

  factory :user do
    login "blah"
  end

  factory :techtype do
    name "blah"
    example "bleh"
  end
end

然而,FactoryGirl.create(:part)似乎不起作用:

2.0.0p353 :001 > part = FactoryGirl.create(:part)
[SQL insert for State, User, and Techtype outputs here and succeeds, then...]
ActiveRecord::RecordInvalid: Validation failed: 
   State can't be blank, Techtype can't be blank, User can't be blank

我已尝试删除_id属性(即association :state, factory: :state),但这也不起作用,我只得到NoMethodError: undefined method 'state=' for #<Part:0x007fa3e8e798a0>。我也尝试过使用短格式关联(例如state而不是association :state_id, factory: :state),但我得到了相同的NoMethodError

1 个答案:

答案 0 :(得分:3)

您的模型应如下所示

class Part < ActiveRecord::Base
  belongs_to :state
  belongs_to :user
  belongs_to :techtype
end 

你的工厂就是这样

 factory :part do
    name "blah"
    association :state
    association :user
    association :techtype
  end