【问题标题】:How do I mock a block argument in RSpec?如何在 RSpec 中模拟块参数?
【发布时间】:2021-11-27 22:46:53
【问题描述】:

假设我在 ruby​​ 中调用一个带有块参数的 Ruby 方法:

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

如何测试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

但我不知道如何测试在块中调用了 #upload!

【问题讨论】:

    标签: ruby-on-rails ruby rspec rspec-rails


    【解决方案1】:

    使用 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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      相关资源
      最近更新 更多