如何在 RSpec 中模拟块参数?

Mar*_*ins 5 ruby rspec ruby-on-rails rspec-rails

假设我正在用 ruby​​ 中的块参数调用 Ruby 方法:

  Net::SFTP.start('testhost.com', 'test_user', keys: ['key']) do |sftp|
    sftp.upload!('/local', '/remote')
  end
Run Code Online (Sandbox Code Playgroud)

如何测试该upload!方法是否使用正确的参数调用?

我可以走到这一步,测试以下论点#start

  expect(Net::SFTP).
    to receive(:start) do |host, username, keyword_args, &block|
      expect(host).to eq("testhost.com")
      expect(username).to eq("test_user")
      expect(keyword_args).to eq(keys: ["test_key"])
    end
Run Code Online (Sandbox Code Playgroud)

但我不知道如何测试#upload!块中调用的内容。

Bro*_*tse 3

利用- 当与和匹配器and_yield结合使用时效果最佳:allow().to receivehave_received

sftp = spy
allow(Net::SFTP).to receive(:start).and_yield(sftp)

# execute your code here

expect(Net::SFTP).to have_received(:start).with("testhost.com", "test_user", keys: ["test_key"])
expect(sftp).to have_received(:upload!).with('./local', '/remote')
Run Code Online (Sandbox Code Playgroud)