diff --git a/README.md b/README.md index 3adfe84..1de783c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_822 TILs and counting..._ +_823 TILs and counting..._ --- @@ -648,6 +648,7 @@ _822 TILs and counting..._ - [Last Raised Exception In The Call Stack](ruby/last-raised-exception-in-the-call-stack.md) - [Limit Split](ruby/limit-split.md) - [Listing Local Variables](ruby/listing-local-variables.md) +- [Mock Method Chain Calls With RSpec](ruby/mock-method-chain-calls-with-rspec.md) - [Mocking Requests With Partial URIs Using Regex](ruby/mocking-requests-with-partial-uris-using-regex.md) - [Navigate Back In The Browser With Capybara](ruby/navigate-back-in-the-browser-with-capybara.md) - [Next And Previous Floats](ruby/next-and-previous-floats.md) diff --git a/ruby/mock-method-chain-calls-with-rspec.md b/ruby/mock-method-chain-calls-with-rspec.md new file mode 100644 index 0000000..23f19bd --- /dev/null +++ b/ruby/mock-method-chain-calls-with-rspec.md @@ -0,0 +1,31 @@ +# Mock Method Chain Calls With RSpec + +Generally with RSpec you mock one method call at a time: + +```ruby +allow(User).to receive(:new).and_return(true) +``` + +Sometimes you are dealing with code that involves a chain of method calls. + +```ruby +User + .new + .approve + .send_welcome_email +``` + +If it becomes unreasonable to mock out each individual method, you can instead +mock out the chain of calls. + +```ruby +allow(User).to receive_message_chain('new.approve.send_welcome_email') +``` + +Alternatively, you can write this as: + +```ruby +allow(User).to receive_message_chain(:new, :approve, :send_welcome_email) +``` + +[source](https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains)