Rails3 FactoryGirl has_one未知属性错误

时间:2012-08-30 15:27:41

标签: ruby-on-rails ruby-on-rails-3 rspec factory-bot has-one

我有以下设置:

型号:

class Product < ActiveRecord::Base
  has_one :product_category

  attr_accessible :name, :product_category, :product_category_id
end

class ProductCategory < ActiveRecord::Base
  belongs_to :product

  attr_accessible :name

end

迁移:

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.references :product_category
      t.string :name

      t.timestamps
    end
  end
end

class CreateProductCategories < ActiveRecord::Migration
  def change
    create_table :product_categories do |t|
      t.string :name

      t.timestamps
    end
  end
end

现在,我想使用FactoryGirl和RSpec测试它。所以我设置了以下FactoryGirl测试模型:

product_spec.rb

require 'factory_girl'
FactoryGirl.define do
  factory :product, class: Product do
    product_category {|a| a.association(:product_category)}
    name "Demo Product"
  end
end

product_category_spec.rb

require 'factory_girl'
FactoryGirl.define do
  factory :product_category, class: ProductCategory do
    name "Demo Product"
  end
end

但是当我在product_spec.rb上运行RSpec时,我收到以下错误:

can't write unknown attribute 'product_id'

我无法弄清楚为什么会发生这种情况。如果我从产品工厂中删除product_category,一切正常。

1 个答案:

答案 0 :(得分:2)

您的迁移错误:belongs_to应该将外键设为explained in doc