我的工厂有一个url
字段(用于获取 youtube 嵌入式视频):
factory :commercial do
url 'https://www.youtube.com/watch?v=BTTygyxuGj8'
end
在我的测试中,我试图模拟对 youtube 的请求。我在我的中添加了以下内容spec_helper
:
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
RSpec.configure do |config|
config.before(:suite) do
mock_request
end
end
def mock_request
response = {
author_name: 'Confreaks',
# more attributes omitted ..
}
WebMock.stub_request(:get, /.*youtube.*/).
to_return(status: 200, body: response.to_json, headers: {})
end
在 rspec 配置中注册一次 webmock 是否足以使存根在整个测试套件中可用?为什么我必须对我的工厂这样做:
factory :commercial do
url 'https://www.youtube.com/watch?v=BTTygyxuGj8'
after(:build) do |commercial|
mock_request
end
end
没有after(:build)
,我会收到以下错误:
失败/错误:create(:commercial, WebMock::NetConnectNotAllowedError: Real HTTP 连接被禁用。未注册的请求:...告诉我有关未注册的 youtube 请求以及我应该如何存根它...