2

アジャイル Web チュートリアルに少し変更を加えて進めています。Rails 3.2 で機能テストを実行すると、次のエラーが発生します。

test_should_get_new(OrdersControllerTest):
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: cart, deal

orders_controller_test.rb コードは次のとおりです。

test "should get new" do
  cart = Cart.create
  session[:cart_id] = cart.id
  LineItem.create(cart: cart, deal: deals(:one))

  get :new
  assert_response :success
end

注文の備品は次のとおりです。

one:
  name: MyString
  address: MyText
  email: MyString
  pay_type: Check

ラインアイテムのフィクスチャは次のとおりです。

one:
  deal: one
  order: one

ディールフィクスチャは次のとおりです。

one:
  title: MyString
  description: MyText
  image_url: MyString
  price: 9.99

注文コントローラーのコードは次のとおりです。

def new
  @cart = current_cart
  if @cart.line_items.empty?
    redirect_to store_url, notice: "Your cart is empty"
    return
  end

  @order = Order.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @order }
  end
end

FactoryGirl を使用してみましたが、同じエラー メッセージが表示されます。コードは次のとおりです。

test "should get new" do
  cart = FactoryGirl.build(:cart)
  session[:cart_id] = cart.id
  LineItem.create(cart: cart, deal: deals(:one))

  get :new
  assert_response :success
end

そして FactoryGirl コード:

FactoryGirl.define do  
  factory :cart do
  end
end

FactoryGirl の場合、「ビルド」の代わりに「作成」も試しましたが、同じエラー メッセージが表示されました。

構成で大量割り当てエラーをオフにすることもできますが、適切にテストすることを好むので、むしろそうしません。

何か提案はありますか?

4

2 に答える 2

5

LineItem.create(cart: cart, deal: deals(:one))試す代わりに

item = LineItem.create
item.cart = cart
item.deal = deals(:one)

または LineItem モデルに以下を追加します。

attr_accessible :cart, :deal
于 2012-04-21T15:19:41.873 に答える