RSpec 另一个库的存根方法的存根弃用警告

RSpec stub deprecation warning for stub method of another library

我有一个规范 运行 没有问题,除非我尝试 运行 单个 it 块。在这种情况下,我得到一个 Failure/Error: before(:context) 的解释:

The use of doubles or partial doubles from rspec-mocks outside of the per-test lifecycle is not supported. Using stub from rspec-mocks' old :should syntax without explicitly enabling the syntax is deprecated. Use the new :expect syntax or explicitly enable :should instead.

问题是我不使用 rspec-mocks stub 方法,而是 dry-container:

定义的方法

像这样:

require 'dry/container/stub'

before { FooContainer.enable_stubs! }

before(:context) { FooContainer.stub 'foo.key', stubbed_operation }

after(:context) { FooContainer.unstub 'foo.key' }

有没有办法在不启用旧 rspec-mocks 语法的情况下禁用此 RSpec 行为?


rspec --version
RSpec 3.8
  - rspec-core 3.8.0
  - rspec-expectations 3.8.2
  - rspec-mocks 3.8.0
  - rspec-rails 3.8.2
  - rspec-support 3.8.0


rails -v
Rails 5.2.2.1

ruby -v
ruby 2.6.2p47 (2019-03-13 revision 67232) [x86_64-linux]

dry-container (0.6.0)

我现在找到了一个解决方法,如果我使用:

before { FooContainer.stub 'foo.key', stubbed_operation }

after { FooContainer.unstub 'foo.key' }

而不是:

before(:context) { FooContainer.stub 'foo.key', stubbed_operation }

after(:context) { FooContainer.unstub 'foo.key' }

有效。我能看到的唯一缺点是它会消耗一点性能并且将来可能会崩溃。

我认为问题在于,您在 before(:each) 块中启用了存根,而不是在 before(:context) 块内,它在 before(:each) 块之前执行。此时 dry-containerstub 方法对 rspec/ruby 是未知的,因此它尝试使用 rspec-mock.

的默认 stub 方法
require 'dry/container/stub'

before(:context) { FooContainer.enable_stubs! }
before(:context) { FooContainer.stub 'foo.key', stubbed_operation }

# or better
before(:context) do
  FooContainer.enable_stubs!
  FooContainer.stub 'foo.key', stubbed_operation
end

after(:context) { FooContainer.unstub 'foo.key' }

context "my context" do
  it "my test" do
    ...
  end
end 

来自dry-container testing documentation

# before stub you need to enable stubs for specific container
container.enable_stubs!
container.stub(:redis, "Stubbed redis instance")