2013-07-24 197 views
2

方法我有一個Transaction模型,其中我有以下範圍:破壞測試控制器使用RSpec

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 

而且還有我的Transaction控制器的destroy方法:

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)>' 

你能幫我解答嗎?

+1

老問題,但只是爲其他用戶注意。如果這個錯誤發生,那麼這是因爲在'let!'上使用'let'(它應該是'let!(:ownership)',因爲它保存在數據庫中,':count'會有意義),第二個原因可能是控制器中的邏輯失敗(這個測試應該在任何情況下進行測試:)) – Aleks

回答

0

從RSpec的文檔有letlet!see here)之間的差異; '讓我們!'

使用let來定義memoized幫助器方法。該值將在同一個示例中跨多個調用緩存 ,但不會跨越示例。

請注意,let是懶惰評估的:直到第一個調用它所定義的方法的時間纔會被評估。你可以用let!在每個示例之前強制執行 方法的調用。

在您的銷燬方法中,使用let!(:ownership),這樣ownership對象在銷燬後不會被緩存。