Last active
December 15, 2015 12:19
-
-
Save malclocke/5259136 to your computer and use it in GitHub Desktop.
Rspec delegation matcher
This file contains 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 | |
# # post.name -> post.author.name | |
# it { should delegate(:name).to(:author) } | |
# | |
# # post.author_name -> post.author.name | |
# it { should delegate(:author_name).to(:author).as(:name) } | |
# end | |
RSpec::Matchers.define :delegate do |method| | |
match do |delegator| | |
@method = method | |
@delegator = delegator | |
as = @as || @method | |
begin | |
@delegator.send(@to) | |
rescue NoMethodError | |
raise "#{@delegator} does not respond to #{@to}!" | |
end | |
@response = double('response') | |
@receiver = double('receiver') | |
@receiver.stub(as => @response) | |
@delegator.stub(@to => @receiver) | |
@delegator.send(@method) == @response | |
end | |
description do | |
"delegate :#{@method} to its #{@to}#{@as ? " as #{@as}" : ''}" | |
end | |
failure_message_for_should do |text| | |
"expected #{@delegator} to delegate :#{@method} to its #{@to}#{@as ? " as #{@as}" : ''}" | |
end | |
failure_message_for_should_not do |text| | |
"expected #{@delegator} not to delegate :#{@method} to its #{@to}#{@as ? " as #{@as}" : ''}" | |
end | |
chain(:to) { |receiver| @to = receiver } | |
chain(:as) { |as| @as = as } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment