Created
March 27, 2012 21:21
-
-
Save rahearn/2220360 to your computer and use it in GitHub Desktop.
RSpec matcher for "should delegate(:action).to :other_model"
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
# code source: https://github.com/thoughtbot/shoulda/issues/174 | |
RSpec::Matchers.define :delegate do |delegated_method| | |
chain :to do |target_method| | |
@target_method = target_method | |
end | |
chain :as do |method_on_target| | |
@method_on_target = method_on_target | |
end | |
chain :with_arguments do |args| | |
@args = args | |
end | |
match do |instance| | |
extend Mocha::API | |
@instance = instance | |
@args ||= [] | |
return_value = 'stubbed return value' | |
method_on_target = @method_on_target || delegated_method | |
stubbed_target = stub('stubbed_target', method_on_target => return_value) | |
@instance.stubs(@target_method => stubbed_target) | |
begin | |
@instance.send(delegated_method, *@args) == return_value | |
rescue NoMethodError | |
false | |
end | |
end | |
failure_message_for_should do | |
if Class === @instance | |
message = "expected #{@instance.name} " | |
prefix = '.' | |
else | |
message = "expected #{@instance.class.name} " | |
prefix = '#' | |
end | |
message << "to delegate #{prefix}#{delegated_method} to #{prefix}#{@target_method}" | |
if @method_on_target | |
message << ".#{@method_on_target}" | |
end | |
message | |
end | |
description do | |
d = "delegate #{delegated_method}" | |
d << " to #{@target_method}" if @target_method | |
d << " as #{@method_on_target}" if @method_on_target | |
d | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment