我有一個接受invoice
模型及其嵌套items
:如何測試Rails使用嵌套屬性和FactoryGirl創建動作?
class Invoice < ActiveRecord::Base
belongs_to :user
has_many :items
attr_accessible :number, :date, :recipient, :project_id, :items_attributes
accepts_nested_attributes_for :items, :reject_if => :all_blank
end
我覺得很難使用RSpec和FactoryGirl測試這一點,雖然。這是我有:
describe 'POST #create' do
context "with valid attributes" do
it "saves the new invoice in the database" do
expect {
post :create, invoice: attributes_for(:invoice), items_attributes: [ attributes_for(:item), attributes_for(:item) ]
}.to change(Invoice, :count).by(1)
end
end
end
這是我在控制器中創建操作:
def create
@invoice = current_user.invoices.build(params[:invoice])
if @invoice.save
flash[:success] = "Invoice created."
redirect_to invoices_path
else
render :new
end
end
每當我跑,我得到一個錯誤:Can't mass-assign protected attributes: items
任何人可以幫助我在這呢?
謝謝...
啊,看起來比我的版本好多了,謝謝。儘管如此,你的代碼行會導致語法錯誤,所以我刪除了圓括號。這樣,試運行,但仍然拋出了同樣的錯誤:'不是大規模分配進行保護的屬性:items' – Tintin81 2013-03-08 13:08:02
語法是正確的,見參考文獻:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods html的。沒有'item'在我寫的參數,可以我想你拼錯的東西 – apneadiving 2013-03-08 13:12:35
對不起,剛剛意識到的東西,編輯答案 – apneadiving 2013-03-08 13:22:18