Ho un modello di Invoice
che può contenere un certo numero di Items
così:Come creare oggetti di prova con attributi nidificati con FactoryGirl in Ruby on Rails?
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
Sto cercando di verificare questo utilizzando 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
Purtroppo, questo test (e tutti gli altri) fallire con questo messaggio di errore da RSpec:
Failure/Error: @invoice = @user.invoices.create(FactoryGirl.attributes_for(:invoice))
ActiveModel::MassAssignmentSecurity::Error:
Can't mass-assign protected attributes: items
Come posso creare una fattura con articoli che supereranno i miei test?
Sto usando factorygirl per fabbricare oggetti di questo tipo:
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
OK, grazie, ma non ho potuto farlo funzionare in questo modo. – Tintin81