-
-
Save bparanj/4579700adca0b64e7ca0 to your computer and use it in GitHub Desktop.
RSpec matcher for delegations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Possible bug: I believe there is a typo in line 20; I think (:@to)
should be (@to)
I corrected in a fork found here
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
This gist is updated to use the RSpec 3.3 syntax for stub and double.