我有一个测试会产生以下错误:
1) Failure:
test_should_get_create(ProductRequestsControllerTest) [/Users/noahc/Dropbox/mavens/test/functional/product_requests_controller_test.rb:37]:
"ProductRequest.count" didn't change by 1.
<2> expected but was
<1>.
我该如何解决这个问题?具体来说,如何获得更具体的详细错误?
这是我的测试:
test "should get create" do
sign_in(FactoryGirl.create(:user))
assert_difference('ProductRequest.count') do
post :create, product_request: FactoryGirl.attributes_for(:product_request)
end
assert_response :success
end
这是我的控制器:
def create
cart = current_cart
rows = CartRow.find_all_by_cart_id(cart.id)
rows.each do |row|
product_request = ProductRequest.new(params[:product_request])
product_request.user_id = current_user.id
product_request.product_id = row.product_id
product_request.quantity = row.quantity
product_request.save
end
redirect_to root_path
end
我认为问题在于我没有定义购物车。如何创建 unit::test 可以看到的购物车?我曾尝试使用 FactoryGirl 创建购物车,但这似乎不起作用。
carts_factory.rb
FactoryGirl.define do
factory :cart do
end
end
更新测试:
test "should get create" do
sign_in(FactoryGirl.create(:user))
user = FactoryGirl.create(:user)
product = FactoryGirl.create(:product)
assert_difference('ProductRequest.count') do
post :create, product_request: FactoryGirl.attributes_for(:product_request, user: user.id, product: product.id)
end
assert_response :success
end
和 current_cart
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
第二次更新
我已经按照您的建议更新了工厂。
这是我的测试现在的样子:
test "should get create" do
user = FactoryGirl.create(:user)
cart = FactoryGirl.create(:cart_with_1_row)
product = FactoryGirl.create(:product)
sign_in(user)
product = FactoryGirl.create(:product)
assert_difference('ProductRequest.count') do
post :create, { product_request: FactoryGirl.attributes_for(:product_request, user_id: user.id, product_id: product.id, cart_id: cart.id) }
end
assert_response :success
end
这是在测试控制台中:
irb(main):016:0> a = { product_request: FactoryGirl.attributes_for(:product_request, user_id: user.id, product_id: product.id, cart_id: cart.id) }
=> {:product_request=>{:quantity=>10, :street=>"123 street", :city=>"Some City", :state=>"Iowa", :zip=>"13829", :user_id=>1, :product_id=>2, :cart_id=>1}}