`destroy` 对象上的 RSpec 变化带来的意外结果

Un-expected result from RSpec change on `destroy` object

我正在尝试在我的模型上测试 destroy

   subject(:product){ FactoryGirl.create(:product)}

    it "destroys product" do
      expect{product.destroy}.to change(Product,:count).by(-1)
    end

但是失败了。谁能指出我做错了什么?

subject 块被延迟评估。这意味着产品是在首次使用时创建的。完全没有变化,因为你在期望中第一次调用product并立即销毁该记录。

要解决此问题,请确保在预期之前创建记录:

subject(:product) { FactoryGirl.create(:product) }

before { product } # this line creates the product before running the test

it 'destroys product' do
  expect { product.destroy }.to change(Product, :count).by(-1)
end

或者:

subject!(:product) { FactoryGirl.create(:product) } # note the '!'

it 'destroys product' do
  expect { product.destroy }.to change(Product, :count).by(-1)
end