From 3a52fbbe9ddd913dac44dcab8811e0baa395a734 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sat, 13 Apr 2019 09:16:06 -0500 Subject: [PATCH] Add Define A Custom RSpec Matcher as a ruby til --- README.md | 3 ++- ruby/define-a-custom-rspec-matcher.md | 32 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 ruby/define-a-custom-rspec-matcher.md diff --git a/README.md b/README.md index f2f4d38..de2bd0c 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/). -_804 TILs and counting..._ +_805 TILs and counting..._ --- @@ -615,6 +615,7 @@ _804 TILs and counting..._ - [Create Listing Of All Middleman Pages](ruby/create-listing-of-all-middleman-pages.md) - [Create Thumbnail Image For A PDF](ruby/create-thumbnail-image-for-a-pdf.md) - [Defaulting To Frozen String Literals](ruby/defaulting-to-frozen-string-literals.md) +- [Define A Custom RSpec Matcher](ruby/define-a-custom-rspec-matcher.md) - [Destructuring Arrays In Blocks](ruby/destructuring-arrays-in-blocks.md) - [Disassemble Some Codes](ruby/disassemble-some-codes.md) - [Double Splat To Merge Hashes](ruby/double-splat-to-merge-hashes.md) diff --git a/ruby/define-a-custom-rspec-matcher.md b/ruby/define-a-custom-rspec-matcher.md new file mode 100644 index 0000000..6b5ad97 --- /dev/null +++ b/ruby/define-a-custom-rspec-matcher.md @@ -0,0 +1,32 @@ +# Define A Custom RSpec Matcher + +You can define your own custom RSpec matchers. This is a great way to keep +your spec tight and readable. A custom, domain-specific matcher can convey +more intent in a single line than several lines of built-in matchers. + +Here is a matcher to check if something is in a range: + +```ruby +require 'rspec/expectations' + +RSpec::Matchers.define :be_betwen do |lower, upper| + match do |operand| + expect(operand).to be >= lower + expect(operand).to be <= upper + end +end + +describe MyThing do + it "has a value between 0 and 10" do + thing = MyThing.new + + expect(thing.value).to be_between(0, 10) + end +end +``` + +By requiring `rspec/expectations` we are able to define a matcher that takes +0 or more arguments (in our case, `lower` and `upper`) and then make +assertions with them and the `expect` value. + +[source](https://relishapp.com/rspec/rspec-expectations/v/2-4/docs/custom-matchers/define-matcher)