使用WebMock进行Rails Rspec测试。如果不是生产env,Stubbing Class初始化?

时间:2016-01-12 17:56:31

标签: ruby-on-rails testing rspec webmock

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

我的用例是我有一个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的初始化等于' stubbed'。它投掷的具体错误是:

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>

我有什么明显的遗失吗?

1 个答案:

答案 0 :(得分:0)

您需要定义foo_bar,如

foo_bar = FooBar.new

然后在代码中使用它。

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

OR

你也可以为任何FooBar实例推广它。然后创建它的实例以在测试中使用。

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