Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

376
Views
How do I mock a block argument in RSpec?

Let's say I am calling a Ruby method with a block argument in ruby:

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

How can I test that the upload! method was called with the correct arguments?

I could get this far, testing the arguments for #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

But I can't figure out how to test that #upload! was called in the block.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Make use of and_yield - this works best when combined with allow().to receive and have_received matcher:

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')
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!