Today I Learned

hashrocket A Hashrocket project

Yield a double to a Block in RSpec

TIL in rspec you can yield a double to a block with and_yield, similar to how you return a double with and_return.

With and_return you can write a test like this:

sftp = Net::SFTP.start(args)
sftp.upload!(content, path)

# Test
client = double
allow(Net::SFTP).to receive(:start).and_return(client)
expect(client).to receive(:upload!)

However, if your code has a block like below and_return won't work. Instead, you can use and_yield to yield the double to the block:

Net::SFTP.start(args) do |sftp|
  sftp.upload!(content, path)
end

# Test
client = double
allow(Net::SFTP).to receive(:start).and_yield(client)
expect(client).to receive(:upload!)

Docs

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.