Skip to content

Instantly share code, notes, and snippets.

@bparanj
Forked from txus/delegate_matcher.rb
Created November 3, 2015 23:55
Show Gist options
  • Save bparanj/4579700adca0b64e7ca0 to your computer and use it in GitHub Desktop.
Save bparanj/4579700adca0b64e7ca0 to your computer and use it in GitHub Desktop.
RSpec matcher for delegations
# RSpec matcher to spec delegations.
#
# Usage:
#
# describe Post do
# it { should delegate(:name).to(:author).with_prefix } # post.author_name
# it { should delegate(:month).to(:created_at) }
# it { should delegate(:year).to(:created_at) }
# end
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('receive'))
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
@bparanj
Copy link
Author

bparanj commented Nov 3, 2015

This gist is updated to use the RSpec 3.3 syntax for stub and double.

@robvitaro
Copy link

Possible bug: I believe there is a typo in line 20; I think (:@to) should be (@to)

I corrected in a fork found here

@purp
Copy link

purp commented Dec 29, 2016

Another probably bug: line 21, should be receive(@method) else when @Prefix is true, you attempt with the wrong method name.

Refactored a bit for RSpec 3.5 and simplicity in yet another fork.

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