用rspec测试控制器中的破坏方法

时间:2013-07-24 09:12:35

标签: ruby-on-rails rspec controller

我有一个Transaction模型,其中我有以下范围:

scope :ownership, -> { where property: true }

我对控制器进行了一些测试(感谢M. Hartl)。他们在那里:

require 'spec_helper'

describe TransactionsController do

  let(:user) { FactoryGirl.create(:user) }
  let(:product) { FactoryGirl.create(:givable_product) }

  before { be_signed_in_as user }

  describe "Ownerships" do

    describe "creating an ownership with Ajax" do

      it "should increment the Ownership count" do
        expect do
          xhr :post, :create, transaction: { property: true, user_id: user.id, product_id: product.id }
        end.to change(Transaction.ownership, :count).by(1)
      end

      it "should respond with success" do
        xhr :post, :create, transaction: { property: true, user_id: user.id, product_id: product.id }
        expect(response).to be_success
      end
    end

    describe "destroying an ownership with Ajax" do
      let(:ownership) { user.transactions.ownership.create(product_id: product.id, user_id: user.id) }

      it "should decrement the Ownership count" do
        expect do
          xhr :delete, :destroy, id: ownership.id
        end.to change(Transaction.ownership, :count).by(-1)
      end

      it "should respond with success" do
        xhr :delete, :destroy, id: ownership.id
        expect(response).to be_success
      end
    end
  end
end

我的destroy控制器有Transaction方法:

def destroy
  @transaction = Transaction.find(params[:id])
  @property = @transaction.property
  @product = @transaction.product
  @transaction.destroy
  respond_to do |format|
    format.html { redirect_to @product }
    format.js
  end
end      

但是当我运行测试时,其中一个失败了,我不明白为什么或为什么:

1) TransactionsController Ownerships destroying an ownership with Ajax should decrement the Ownership count
   Failure/Error: expect do
     count should have been changed by -1, but was changed by 0
   # ./spec/controllers/transactions_controller_spec.rb:31:in `block (4 levels) in <top (required)>'

你能帮我解决一下吗?

2 个答案:

答案 0 :(得分:1)

你可以使用'let!'。

关于'let'和'let!':https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let

答案 1 :(得分:0)

根据RSpec文档,letlet!之间存在差异(see here);

  

使用let来定义memoized帮助器方法。该值将被缓存   在同一个示例中跨多个调用但不跨越示例。

     

请注意,let是惰性计算的:直到第一个才进行评估   调用它定义的方法的时间。你可以用let!迫使   每个例子之前的方法调用。

在你的destroy方法中使用let!(:ownership),以便ownership对象在被销毁后不会被缓存。