I am going through the Agile Web tutorial with some slight changes. When I run functional tests in Rails 3.2, I am getting the following error:
test_should_get_new(OrdersControllerTest):
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: cart, deal
Here is the orders_controller_test.rb code:
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
Here is the orders fixtures:
one:
name: MyString
address: MyText
email: MyString
pay_type: Check
Here is the line items fixtures:
one:
deal: one
order: one
Here is the deals fixture:
one:
title: MyString
description: MyText
image_url: MyString
price: 9.99
Here is the order controller code:
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
I tried using FactoryGirl but still got the same error message. Here is the code:
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
And the FactoryGirl code:
FactoryGirl.define do
factory :cart do
end
end
For FactoryGirl I also tried ‘create’ instead of ‘build’ and got the same error message.
Although I could turn off the mass assignment error in config, I would rather not since I prefer to test properly.
Any suggestions please?
Instead of
LineItem.create(cart: cart, deal: deals(:one))tryor in your LineItem model, add: