在这里做了一些研究并使用谷歌之后,我仍然对为什么这个简单的规范不起作用感到困惑:
describe CartsController do
#stuff omitted...
describe "carts#destroy" do
it "destroys the requested cart" do
cart = FactoryGirl.create(:cart)
puts "Cart count = #{Cart.count}"
expect {
delete :destroy, :id => cart.id
}.to change(Cart, :count).by(-1)
end
end
#stuff omitted...
end
这是 CartsController 的操作:
class CartsController < ApplicationController
def destroy
@cart = current_cart
@cart.destroy
session[:cart_id] = nil
respond_to do |format|
format.html { redirect_to(store_url, :notice => 'Your cart is currently empty') }
format.json { head :ok }
end
end
end
最后但并非最不重要的是,我得到的错误:
Cart count = 1
F
Failures:
1) CartsController carts#destroy destroys the requested cart
Failure/Error: expect {
count should have been changed by -1, but was changed by 0
# ./spec/controllers/carts_controller_spec.rb:146:in `block (3 levels) in <top (required)>'
Finished in 6.68 seconds
1 example, 1 failure
但是,我是 rspec 测试的新手,据我了解,我的销毁规范非常简单,它应该按预期执行。我不知道我做错了什么..
请帮助我,一如既往的感谢,
编辑..这是 current_cart 方法:
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end