在rspec中删除测试 - 更改(模型,:计数)失败 - 为什么需要重新加载?

Dav*_*mpy 6 ruby testing rspec ruby-on-rails

TLDR:App.count需要重新加载才能查看创建的记录.为什么?

我发现很多引用测试DELETE方法,如下所示:

expect { delete_request }.to change(App, :count).by(-1)
Run Code Online (Sandbox Code Playgroud)

这是有道理的,并且适用于某些类似的场景.但是,在测试不应该工作的删除时,我发现了一个问题,例如没有用户登录时.

这是我开始的地方,有两种方法来测试同一件事:

require 'rails_helper'

RSpec.describe V1::AppsController, type: :controller do
  let(:user) { create(:user) }
  let(:app) { create(:app, account: user.account) }

  describe 'DELETE destroy when you are not logged in' do
    let(:delete_request) { delete :destroy, id: app, format: :json }

    it 'does not delete the app (.count)' do
      expect { delete_request }.not_to change(App, :count)
    end

    it 'does not delete the app (.exists?)' do
      delete_request
      expect(App.exists?(app.id)).to eq(true)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这就是rspec所说的:

V1::AppsController
  DELETE destroy when you are not logged in
    does not delete the app (.count) (FAILED - 1)
    does not delete the app (.exists?)

Failures:

  1) V1::AppsController DELETE destroy when you are not logged in does not delete the app (.count)
     Failure/Error: expect { delete_request }.not_to change(App, :count)
       expected #count not to have changed, but did change from 0 to 1
     # ./spec/controllers/v1/delete_test_1.rb:11:in `block (3 levels) in <top (required)>'

2 examples, 1 failure
Run Code Online (Sandbox Code Playgroud)

注意最令人困惑的部分:expected #count not to have changed, but did change from 0 to 1.咦?我试图进行非法删除,我的记录数增加了一倍?另请注意,明确检查主题记录的检查仍然存在.

所以我玩了一些,发现我可以在expect()之前重新加载修复问题:

it 'does not delete the app (.count)' do
  puts "App.count is #{App.count} (after create(:app))"
  app.reload
  puts "App.count is #{App.count} (after reload)"
  expect { delete_request }.not_to change(App, :count)
  puts "App.count is #{App.count} (after request)"
end
Run Code Online (Sandbox Code Playgroud)

现在rspec很高兴:

V1::AppsController
  DELETE destroy when you are not logged in
App.count is 0 (after create(:app))
App.count is 1 (after reload)
App.count is 1 (after request)
    does not delete the app (.count)
    does not delete the app (.exists?)

2 examples, 0 failures
Run Code Online (Sandbox Code Playgroud)

从这一切来看,我决定坚持这种exists?方法.但是另一个(可能更大)的关注点是,我在互联网上发现的所有测试样本都expect { create_request }.to change(App, :count).by(1)可能是误报,如果他们看到的结果与我相同,并假设记录是在事实上创建的这是一个缓存工件?

那么,任何想法为什么App.count需要reload查看当前值?

Rod*_*igo 7

发生这种情况是因为当ruby调用该delete_request方法时,它会调用该app方法,并创建一个方法App

要测试它,请在调用expectrspec方法之前创建应用程序:

it 'does not delete the app (.count)' do
  app #creates the app
  expect { delete_request }.not_to change(App, :count)
end
Run Code Online (Sandbox Code Playgroud)

看看let文档:

使用let来定义memoized帮助器方法.该值将在同一示例中的多个调用之间缓存,但不跨示例缓存.

请注意,let是惰性求值的:直到第一次调用它定义的方法时才会对它进行求值.你可以用let!在每个示例之前强制执行方法的调用.

https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/helper-methods/let-and-let