Skip to content

Instantly share code, notes, and snippets.

@malclocke
Last active December 15, 2015 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malclocke/5259136 to your computer and use it in GitHub Desktop.
Save malclocke/5259136 to your computer and use it in GitHub Desktop.
Rspec delegation matcher
# 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