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

Add Define A Custom RSpec Matcher as a ruby til

This commit is contained in:
jbranchaud
2019-04-13 09:16:06 -05:00
parent 96690f66cc
commit 3a52fbbe9d
2 changed files with 34 additions and 1 deletions

View File

@@ -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)