2

我有一个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)>'

你能帮帮我吗?

4

2 回答 2

1

您可以使用“让!”。

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

于 2013-11-27T03:07:58.330 回答
0

let从 RSpec 文档来看,和之间有区别let!请参见此处);

使用 let 定义一个记忆化的辅助方法。该值将在同一示例中的多个调用中缓存,但不会跨示例缓存。

注意 let 是惰性求值的:直到它定义的方法第一次被调用时才会求值。你可以使用让!在每个示例之前强制调用方法。

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

于 2014-10-14T09:38:15.487 回答