From 9280e1fd38978f0ebb14e409007f3992c31b6141 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Fri, 1 Oct 2021 13:11:52 -0500 Subject: [PATCH] Add Check Specific Arguments To Received Method as an RSpec til --- README.md | 7 +++- ...k-specific-arguments-to-received-method.md | 40 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 rspec/check-specific-arguments-to-received-method.md diff --git a/README.md b/README.md index 66300fe..45b824b 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/rspec/check-specific-arguments-to-received-method.md b/rspec/check-specific-arguments-to-received-method.md new file mode 100644 index 0000000..ff97a95 --- /dev/null +++ b/rspec/check-specific-arguments-to-received-method.md @@ -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.