1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Check Specific Arguments To Received Method as an RSpec til

This commit is contained in:
jbranchaud
2021-10-01 13:11:52 -05:00
parent 2607d4e347
commit 9280e1fd38
2 changed files with 46 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1156 TILs and counting..._
_1157 TILs and counting..._
---
@@ -47,6 +47,7 @@ _1156 TILs and counting..._
* [React Native](#react-native)
* [React Testing Library](#react-testing-library)
* [ReasonML](#reasonml)
* [RSpec](#rspec)
* [Ruby](#ruby)
* [sed](#sed)
* [Shell](#shell)
@@ -870,6 +871,10 @@ _1156 TILs and counting..._
- [Using Optional Labeled Function Arguments](reason/using-optional-labeled-function-arguments.md)
- [Wrapping A Component For Use In JavaScript](reason/wrapping-a-component-for-use-in-javascript.md)
### RSpec
- [Check Specific Arguments To Received Method](rspec/check-specific-arguments-to-received-method.md)
### Ruby
- [A Basic Case Statement](ruby/a-basic-case-statement.md)

View File

@@ -0,0 +1,40 @@
# Check Specific Arguments To Received Method
Let's say we have a method receiving a big hash of arguments. A hash like this:
```ruby
{
name: 'Taco Tray',
product_id: 'taco123',
price: 4500,
description: 'A big tray of tacos',
discounts: {
coupon: 'DISCOUNT_TACOS'
}
}
```
In an RSpec test we want to check one of those hash values in a certain
scenario. It can be tedious to type out and check the entire hash. Instead, we
want the test to surgically check just one part of the hash.
We can do this with RSpec's dynamic matcher syntax. The [`hash_including`
argument
matcher](https://rspec.info/documentation/3.4/rspec-mocks/RSpec/Mocks/ArgumentMatchers.html#hash_including-instance_method)
can be nested within the `#with` part of `expect().to receive().with()`.
```ruby
expect(TacoTruck)
.to receive(:take_order)
.with(
hash_including(
discounts: { coupon: 'DISCOUNT_TACOS'}
)
)
```
This will assert about the `discounts` portion of the hash that `#take_order`
gets called with. The rest of the hash will be ignored.
Without `hash_including`, the `with` call would result in a failure when trying
to match against the entire hash.