【问题标题】:Rails Rspec Testing with WebMock. Stubbing Class initialize if not production env?使用 WebMock 进行 Rails Rspec 测试。如果不是生产环境,存根类初始化?
【发布时间】:2016-01-12 17:56:31
【问题描述】:

我是测试新手,在测试外部依赖响应时遇到了一些问题。

我的用例是我有一个 gem Foo,它根据传入的数据发回一些数据。我在初始化类 FooBar 时使用这个 gem。其代码与此类似:

require 'foo'
class FooBar
  attr_accessor :thing

  def initialize(name)
    @thing = Foo(thing)
  end
end

我希望能够在我的 rails 测试环境中存根 FooBar 的类初始化,但允许在我的生产环境中处理外部请求。在我的测试环境中,我只想传回具有预先提供的值的 FooBar 实例。现在我只是想传回一个字符串。

我现在正在尝试使用 WebMock gem 来存根 FooBar 的初始化:

require 'webmock/rspec'
  WebMock.disable_net_connect!(allow_localhost: true)

  RSpec.configure do |config|
    config.before(:each) do
      allow(foo_bar).to receive(:new).and_return('stubbed')
    end
  end
end

在我的 spec_helper 文件中,我的测试检查 FooBar 的初始化是否等于“存根”。它抛出的具体错误是:

FooBar When I initialize class FooBar should be a string
FooBar
Failure/Error: Unable to find matching line from backtrace
NameError:
undefined local variable or method `foo_bar' for 
#<RSpec::ExampleGroups::FooBar::WhenIInitializeClassFooBar>

我有什么明显的遗漏吗?

【问题讨论】:

    标签: ruby-on-rails testing rspec webmock


    【解决方案1】:

    你需要定义 foo_bar 之类的

    foo_bar = FooBar.new
    

    然后像在你的代码中一样使用它。

    allow(foo_bar).to receive(:new).and_return('stubbed')
    

    您也可以将其推广到任何 FooBar 实例。然后创建它的实例以在您的测试中使用。

    allow_any_instance_of(FooBar).to receive(:new).and_return('stubbed')
    

    【讨论】:

    • 这两者仍然会进行外部调用,在 Rails 测试环境中运行时会中断。 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多