【问题标题】:RSpec stub deprecation warning for stub method of another library另一个库的存根方法的 RSpec 存根弃用警告
【发布时间】:2019-04-17 22:32:49
【问题描述】:

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

在 rspec-mocks 之外使用双打或部分双打 不支持每个测试生命周期。使用来自 rspec-mocks 的stub 没有显式启用语法的旧 :should 语法是 已弃用。使用新的:expect 语法或显式启用 :should 代替。

问题是我不使用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)

【问题讨论】:

  • 这是最近开始的吗?你的 Gemfile.lock 改变了吗?
  • @lacostenycoder 我今天添加了有问题的代码,所以是的,它最近开始了,但与此同时我没有更改我的Gemfile.lock。我用相关的 gem 版本编辑了我的问题。
  • 这里有什么有用的吗? github.com/rspec/rspec-mocks/blob/…
  • @lacostenycoder 基本上是我不想更改的配置选项,因为我想在其他地方得到警告。我发现一种解决方法很困难,只需要一点性能。谢谢你的帮助!!

标签: ruby-on-rails ruby unit-testing rspec


【解决方案1】:

我认为问题在于,您在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")

【讨论】:

  • 我认为您需要在第一段中将before(:each)before(:context) 交换,因为我现在使用的解决方法是使用before/ before(:each) 而不是before(:context)
  • @wintersolutions 我的缩进是回答您的问题(而不是您的解决方法)。无论如何,关键是您需要先调用.enable_stubs!,然后才能从dry-container 使用.stub。这取决于您的设置,如果您想在 before(:context)before(:each) 块内执行此操作。
  • 是的,我现在理解并同意 100%。 Grüße
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2012-10-24
    • 2014-09-23
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 2021-03-15
    • 2016-03-03
    相关资源
    最近更新 更多