Tag: stubbing

请求正文不同时的存根请求

嗨,我正在使用ruby-2.5.0和Rails 5处理RoR项目。我正在使用stub_request来存储一个http请求。 此http请求基本上是发送电子邮件的mailjet api请求。 所以,我不能只重复使用片段,rspec吐出来,因为身体每次执行都不同。 存根请求 stub_request(:post, “https://api.mailjet.com/v3/send”). with( body: “{\”FromEmail\”:\”abc@abc.ocm\”,\”FromName\”:\”abc\”,\”To\”:\”abc@abc.com\”,\”Subject\”:\”Forgot Password\”,\”Text-part\”:\”xV3SEtaoa1oyYYfYBt12pw\”}”, headers: { ‘Accept’=>’application/json’, ‘Accept-Encoding’=>’deflate’, ‘Authorization’=>’Basic YmY0NzdhZmYyMmZlMGQwMzAxNzYzNDNkODUwZTY1MzE6YmRhNmZmYzQ0Y2ZmNGM3MmZkZGNkMjUwODA5YWJhZjM=’, ‘Content-Length’=>’143’, ‘Content-Type’=>’application/json’, ‘Host’=>’api.mailjet.com’, ‘User-Agent’=>’mailjet-api-v3-ruby/1.5.4’ }). to_return(status: 200, body: “”, headers: {}) 这里Text-part对每个用户都不同。 我尝试了hash_including方法如下: – stub_request(:post, “https://api.mailjet.com/v3/send”). with( body: hash_including({“FromEmail”: “abc@abc.com”,”FromName”: “abc”}), headers: { ‘Accept’=>’application/json’, ‘Accept-Encoding’=>’deflate’, ‘Authorization’=>’Basic YmY0NzdhZmYyMmZlMGQwMzAxNzYzNDNkODUwZTY1MzE6YmRhNmZmYzQ0Y2ZmNGM3MmZkZGNkMjUwODA5YWJhZjM=’, ‘Content-Length’=>’143’, ‘Content-Type’=>’application/json’, ‘Host’=>’api.mailjet.com’, ‘User-Agent’=>’mailjet-api-v3-ruby/1.5.4’ }). to_return(status: 200, body: “”, headers: […]

用Rspec绑定File.open

我正在尝试存根File.open以测试我读取CSV文件的方法。 这是模型: class BatchTask def import(filename) CSV.read(filename, :row_sep => “\r”, :col_sep => “,”) end end 这是规范代码: let(:data) { “title\tsurname\tfirstname\rtitle2\tsurname2\tfirstname2\r”} let(:result) {[[“title”,”surname”,”firstname”],[“title2″,”surname2″,”firstname2”]] } it “should parse file contents and return a result” do File.stub(:open).with(“file_name”,”rb”) { StringIO.new(data) } person.import(“file_name”).should == result end 但是,当我尝试这样做时,我得到(stacktrace): Errno::ENOENT in ‘BatchTask should parse file contents and return a result’ No such file […]

在RSpecunit testing期间存根地址编码

我正在使用地理编码器 gem为我的一个Active Record模型类添加地理编码function。 这很好用,但我实际上并不希望在unit testing期间触发地理编码。 我已经尝试通过将其添加到我的RSpec测试来删除对地理编码的调用: 之前(:每个)做 User.stub!(:geocode).and_return([1,1])结束 但是,当我运行我的测试时,它仍然似乎在呼唤地理编码。 我究竟做错了什么? 仅供参考,如果我在实例级别存根(例如some_user.stub!而不是User.stub!),这一切都有效。

有没有办法用Rspec存根包含模块的方法?

我有一个包含在另一个模块中的模块,它们都实现了相同的方法。 我想存根包含模块的方法,如下所示: module M def foo :M end end module A class << self include M def foo super end end end describe "trying to stub the included method" do before { allow(M).to receive(:foo).and_return(:bar) } it "should be stubbed when calling M" do expect(M.foo).to eq :bar end it "should be stubbed when calling A" do […]

stub方法仅在第一次使用Rspec调用时

如何仅在第一次调用时存根方法,在第二次调用中它应按预期运行? 我有以下方法: def method do_stuff rescue => MyException sleep rand retry end 我想第一次调用do_stuff来引发MyException ,但在第二次调用中,行为正常。 我需要实现这个来测试我的rescue块而不会得到无限循环。 有没有办法实现这个目标?