Skip to content

Instantly share code, notes, and snippets.

@benoittgt
Created July 14, 2020 19:50
Show Gist options
  • Save benoittgt/480d0a8711058cf6ddf06148f0a89508 to your computer and use it in GitHub Desktop.
Save benoittgt/480d0a8711058cf6ddf06148f0a89508 to your computer and use it in GitHub Desktop.
RSpec EQ and Yield
begin
require "bundler/inline"
rescue LoadError => e
$stderr.puts "Bundler version 1.10 or later is required. Please update your Bundler"
raise e
end
gemfile(true) do
source "https://rubygems.org"
gem "rspec"
end
require 'rspec/autorun'
RSpec.configure do |rspec|
rspec.default_formatter = 'doc'
end
# https://twitter.com/kennethmayer/status/1283084667843776515
# Rspec Twitter: Is it possible to write a custom matcher that also yields to a given block?
RSpec.describe do
RSpec::Matchers.define :eq_and_yield do |expected, blk|
match do |actual|
actual == expected
end
failure_message_for_should do |actual|
"expected that actual: #{blk.call(actual)} would be a eq of #{blk.call(expected)}"
end
end
it do
blk = ->(u) { "arg class: #{u.class}" }
expect('u').to eq_and_yield(:u, blk)
end
end
@benoittgt
Copy link
Author

Failures:

  1) is expected to eq and yield :u and #<Proc:0x00007fccd461d6d8 custom_matcher_yield.rb:34 (lambda)>
     Failure/Error: expect('u').to eq_and_yield(:u, blk)
       expected that actual: arg class: String would be a eq of arg class: Symbol
     # custom_matcher_yield.rb:35:in `block (2 levels) in <main>'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment