rspec-expectations icon indicating copy to clipboard operation
rspec-expectations copied to clipboard

Improve docs for "Custom Matcher from scratch"

Open elado opened this issue 10 years ago • 3 comments

When creating a custom matcher and using it with a mock argument expectation, the === method should also be defined, otherwise, the match will fail.

Example:

expect(instance).to receive(:method).with(a_matcher(1))

Documentation here - http://rubydoc.info/github/rspec/rspec-expectations/RSpec/Matchers Under Custom Matcher from scratch

Add this code to the class:

class BeInZone
  def initialize(expected)
    @expected = expected
  end

  # ...

  alias === matches?

  # ...
end

Alternatively, rspec-mocks should see if this is a matcher and use matches?.

elado avatar Aug 15 '14 20:08 elado

A better approach is to include RSpec::Matchers::Composable; it defines the === alias and provides some other functionality to help use the matcher in composable fashion.

I agree the docs could be improved, though....want to open a PR to improve it?

myronmarston avatar Aug 15 '14 20:08 myronmarston

We may want to link to the matcher protocol that was add in #567.

@elado thanks for reporting this, does lib/rspec/matchers/matcher_protocol.rb provide the details you seek?

cupakromer avatar Aug 16 '14 15:08 cupakromer

We may want to link to the matcher protocol that was add in #567.

That would be good. I also think the examples should be updated to show that we recommend including RSpec::Matchers::Composable as it's intended to be mixed into every matcher class so that it supports the full composability features of matchers in RSpec 3.

myronmarston avatar Aug 16 '14 20:08 myronmarston

Closing due to inactivity during the monorepo migration, but documentation improvements are always welcome.

JonRowe avatar Nov 27 '24 21:11 JonRowe