1

ここでいくつかの調査を行い、Google を使用した後、この単純な仕様が機能しない理由についてまだ混乱しています。

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
4

2 に答える 2