Skip to content

Commit 59408a0

Browse files
committed
Add Mock Method Chain Calls With RSpec as a ruby til
1 parent 2215ebc commit 59408a0

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010
For a steady stream of TILs from a variety of rocketeers, checkout
1111
[til.hashrocket.com](https://til.hashrocket.com/).
1212

13-
_822 TILs and counting..._
13+
_823 TILs and counting..._
1414

1515
---
1616

@@ -648,6 +648,7 @@ _822 TILs and counting..._
648648
- [Last Raised Exception In The Call Stack](ruby/last-raised-exception-in-the-call-stack.md)
649649
- [Limit Split](ruby/limit-split.md)
650650
- [Listing Local Variables](ruby/listing-local-variables.md)
651+
- [Mock Method Chain Calls With RSpec](ruby/mock-method-chain-calls-with-rspec.md)
651652
- [Mocking Requests With Partial URIs Using Regex](ruby/mocking-requests-with-partial-uris-using-regex.md)
652653
- [Navigate Back In The Browser With Capybara](ruby/navigate-back-in-the-browser-with-capybara.md)
653654
- [Next And Previous Floats](ruby/next-and-previous-floats.md)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Mock Method Chain Calls With RSpec
2+
3+
Generally with RSpec you mock one method call at a time:
4+
5+
```ruby
6+
allow(User).to receive(:new).and_return(true)
7+
```
8+
9+
Sometimes you are dealing with code that involves a chain of method calls.
10+
11+
```ruby
12+
User
13+
.new
14+
.approve
15+
.send_welcome_email
16+
```
17+
18+
If it becomes unreasonable to mock out each individual method, you can instead
19+
mock out the chain of calls.
20+
21+
```ruby
22+
allow(User).to receive_message_chain('new.approve.send_welcome_email')
23+
```
24+
25+
Alternatively, you can write this as:
26+
27+
```ruby
28+
allow(User).to receive_message_chain(:new, :approve, :send_welcome_email)
29+
```
30+
31+
[source](https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/message-chains)

0 commit comments

Comments
 (0)