【问题标题】:FactoryGirl Associations工厂女孩协会
【发布时间】:2013-12-20 17:43:24
【问题描述】:

我正在开发一个非常基本的 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

【问题讨论】:

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


    【解决方案1】:

    你的模型应该是这样的

    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
    

    【讨论】:

    • 原来在查看我的代码后,我在 Part 类中遗漏了 belongs_to 属性。第一次与 ActiveRecord 进行关联,所以我错过了。谢谢
    • 对于较新的 factory_girl 语法:factory :part do name "blah" state user techtype end 假设您有名称为 state、user 和 techtype 的工厂。 FactoryGirl 将知道如何完成剩下的工作。
    猜你喜欢
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多