我是测试新手,在测试外部依赖响应时遇到了一些问题。
我的用例是我有一个 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>
我有什么明显的遗漏吗?