2013-03-04 15 views
13

私もItemsの数を含むことがInvoiceモデルを持っている:Ruby on RailsでFactoryGirlでネストされた属性を持つテストオブジェクトを作成するにはどうすればよいですか?

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 

私は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 

残念ながら、このテスト(および他のすべて) RSpecからのこのエラーメッセージで失敗します。

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

テストに合格するアイテムで請求書を作成するにはどうすればよいですか?

私はこのような物体を製造するためにFactoryGirlを使用しています:

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 

答えて

4

は、これは私がそれを理解しようとしていたとき、私はブックマークスタックの答えです:

factory-girl-nested-factory

編集:申し訳ありませんが、答えは純粋なFactoryGirlで、rspecではないことが分かりました。

+0

ありがとう、しかし、私はそれをそのように動作させることができませんでした。 – Tintin81

関連する問題