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