Skip to content

Instantly share code, notes, and snippets.

@schweigert
Created January 4, 2022 18:39
Show Gist options
  • Save schweigert/9650032c4dec2b930e938b7e7220d462 to your computer and use it in GitHub Desktop.
Save schweigert/9650032c4dec2b930e938b7e7220d462 to your computer and use it in GitHub Desktop.
rspec_delegate_matcher.rb
# frozen_string_literal: true
RSpec::Matchers.define :delegate do |method|
match do |delegator|
@method = @prefix ? :"#{@to}_#{method}" : method
@delegator = delegator
begin
@delegator.send(@to)
rescue NoMethodError
raise "#{@delegator} does not respond to #{@to}!"
end
allow(@delegator).to receive(@to).and_return double('receiver')
allow(@delegator.send(@to)).to receive(method).and_return(:called)
@delegator.send(@method) == :called
end
description do
"delegate :#{@method} to its #{@to}#{@prefix ? ' with prefix' : ''}"
end
failure_message do |_text|
"expected #{@delegator} to delegate :#{@method} to its #{@to}#{@prefix ? ' with prefix' : ''}"
end
failure_message_when_negated do |_text|
"expected #{@delegator} not to delegate :#{@method} to its #{@to}#{@prefix ? ' with prefix' : ''}"
end
chain(:to) { |receiver| @to = receiver }
chain(:with_prefix) { @prefix = true }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment