我有一個Invoice
模型可能包含許多Items
還有:如何在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
好的,謝謝,但我無法讓它以這種方式工作。 – Tintin81 2013-03-05 17:11:16