2

我有一個接受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

任何人可以幫助我在這呢?

謝謝...

回答

3

第一:items是嵌套的,所以他們在PARAMS名字是items_attributes。更改。

第二:嵌套意味着...嵌套!

基本上取代:

post :create, invoice: attributes_for(:invoice, items: [ build(:item), build(:item) ]) 

有:

post :create, invoice: { attributes_for(:invoice).merge(items_attributes: [ attributes_for(:item), attributes_for(:item) ]) } 

阿里納斯你在這裏做一個真正的集成測試,你可以存根保留單元測試。

+0

啊,看起來比我的版本好多了,謝謝。儘管如此,你的代碼行會導致語法錯誤,所以我刪除了圓括號。這樣,試運行,但仍然拋出了同樣的錯誤:'不是大規模分配進行保護的屬性:items' – Tintin81 2013-03-08 13:08:02

+0

語法是正確的,見參考文獻:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods html的。沒有'item'在我寫的參數,可以我想你拼錯的東西 – apneadiving 2013-03-08 13:12:35

+0

對不起,剛剛意識到的東西,編輯答案 – apneadiving 2013-03-08 13:22:18

1

我有同樣的問題,所以我創建了一個補丁,增加了一個FactoryGirl.nested_attributes_for方法FactoryGirl:所以現在

module FactoryGirl 
    def self.nested_attributes_for(factory_sym) 
    attrs = FactoryGirl.attributes_for(factory_sym) 
    factory = FactoryGirl.factories[factory_sym] 
    factory.associations.names.each do |sym| 
     attrs["#{sym}_attributes"] = FactoryGirl.attributes_for sym 
    end 
    return attrs 
    end 
end 

您可以撥打:

post :create, invoice: FactoryGirl.nested_attributes_for(:invoice) } 

,你會得到所有你知道,嵌套形式善與愛:)

(要應用,你需要的代碼在我的答案頂部的複製到一個新的文件在你的配置/初始化文件夾中的補丁)

+0

這對我來說非常好。我認爲這應該是被接受的答案。感謝偉大的代碼 – chell 2016-07-22 04:57:42

相關問題