2

invoiceとそのネストされた を受け入れるモデルがありますitems:

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

誰でもこれについて私を助けることができますか?

ありがとう...

4

2 に答える 2

3

First:itemsはネストされているため、params の名前はitems_attributes. それを変更。

2 番目: 入れ子とは、入れ子になっていることを意味します。

基本的に、次を置き換えます。

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) ]) }

サイドノート、あなたはここで実際の統合テストを行っています。単体テストを保持するためにスタブを作成できます。

于 2013-03-08T12:52:25.393 に答える
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) }

そして、あなたが知っていて愛しているネストされたフォームの良さをすべて手に入れることができます:)

(パッチを適用するには、回答の上部にあるそのコードを config/initializers フォルダーの新しいファイルにコピーする必要があります)

于 2013-10-03T21:14:23.423 に答える