How to create test objects with nested attributes with FactoryGirl in Ruby on Rails?
Asked Answered
P

2

14

I have an Invoice model that may contain a number of Items as well:

class Invoice < ActiveRecord::Base

  attr_accessible :number, :date, :recipient, :items_attributes

  belongs_to :user

  has_many :items

  accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true

end

I am trying to test this using RSpec:

describe InvoicesController do

  describe 'user access' do

    before :each do
      @user = FactoryGirl.create(:user)
      @invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
      sign_in(@user)
    end

    it "renders the :show view" do
      get :show
      expect(response).to render_template :show
    end

  end

end

Unfortunately, this test (and all the others) fail with this error message from RSpec:

Failure/Error: @invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: items

How can I create an invoice with items that will pass my tests?

I am using FactoryGirl to fabricate objects like this:

factory :invoice do
  number { Random.new.rand(0..1000000) }
  recipient { Faker::Name.name }
  date { Time.now.to_date }
  association :user
  items { |i| [i.association(:item)] } 
end

factory :item do
  date { Time.now.to_date }
  description { Faker::Lorem.sentences(1) }
  price 50
  quantity 2
end
Paniculate answered 4/3, 2013 at 13:48 Comment(0)
T
5

This is a stack answer I bookmarked when I was trying to figure it out:

factory-girl-nested-factory

Edit: Sorry, just realized the answer was pure FactoryGirl and no rspec.

Tuberose answered 4/3, 2013 at 14:54 Comment(0)
R
1

Have you checked https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#associations?

There's a part about has_many-associations. Basically what it says is to extend your invoice-factory with one that adds some items after it created the invoice.

Retain answered 5/3, 2013 at 20:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.