Search code examples
ruby-on-rails-3rspecrspec2factory-botrspec-rails

Arbitrary attributes error with has_one association and Factory Girl


I'm trying to build a basic shopping cart for a Rails app I'm working on.

Nothing special,
- the shopping cart has many line_items
- each line_item has_one product associated and a quantity with it

 class Cart < ActiveRecord::Base
   attr_accessible :line_items
   has_many :line_items, :dependent => :destroy
 end

 class LineItem < ActiveRecord::Base
   attr_accessible :quantity, :product

   belongs_to :cart
   has_one :product
 end

I'm trying to use RSpec to test this association, but i'm doing something wrong as I'm getting an error that says: DEPRECATION WARNING: You're trying to create an attribute 'line_item_id'. Writing arbitrary attributes on a model is deprecated, and I'm not sure why.

In my factories.rb file I'm defining the line_item factory as follows:

factory :line_item do
  quantity { Random.rand(1..5) }
  product
end

factory :cart do
  factory :cart_with_two_line_items do
    ignore do
      line_item_count 2
    end

    after(:create) do |cart, evaluator|
      FactoryGirl.create_list(:line_item, evaluator.line_item_count, cart_id: cart) # < 104
    end
  end
end

Any pointers where I'm going wrong, it's probably something basic, but I'm still quite new to Rspec. Thanks in advance.

EDIT: line_item_spec.rb

require 'spec_helper'

describe LineItem do
before do
  @line_item = FactoryGirl.create(:line_item)
end

Solution

  • Maybe you forgot to declare the association in the Product model.

    class Product < Activerecord::Base
      belongs_to :line_item
    

    belongs_to will expect that your products table has a column :line_item_id. Have you run your migration and modified the models?