Stub类并返回VCR响应



我有一个类转换器,它调用了类连接器。连接器类确实请求外部API,希望使用VCR记录此API操作,然后在调用转换器中存根连接器类的实例并返回API操作的VCR响应。

class Translator
def initialize
@obj = Connector.new().connect
end
def format
# use obj here for some logic
end
end
class Connector
def connect
# http request to external API
end
end

RSpec.describe Translator, type: :services do
before do
allow_any_instance_of(Connector).to receive(:connect).and_return(VCR recorded response)
end
end

VCR易于使用,可能比您预期的更容易,这就是您遇到问题的原因。

RSpec.describe Translator, type: :services do
it do 
use_vcr_cassette do
expect(Translator.format).to eq 'Foo'
end
end
end

第一次运行规范时,它会发出HTTP请求并将其保存在YAML文件中。下次运行它时,它将使用录制的响应。

这很神奇。更多信息和选项:https://relishapp.com/vcr/vcr/v/1-5-0/docs/test-frameworks/usage-with-rspec

最新更新