From 1ca306e09ecc0582b395c2f1b94c5adcd81b40f9 Mon Sep 17 00:00:00 2001 From: alexs Date: Fri, 9 Aug 2013 13:14:49 +1000 Subject: [PATCH] Added RSpec matchers to test delegations. --- spec/support/matchers/delegate_matchers.rb | 40 ++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 spec/support/matchers/delegate_matchers.rb diff --git a/spec/support/matchers/delegate_matchers.rb b/spec/support/matchers/delegate_matchers.rb new file mode 100644 index 0000000000..4921e3eb99 --- /dev/null +++ b/spec/support/matchers/delegate_matchers.rb @@ -0,0 +1,40 @@ +# 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 + @delegator.stub(@to).and_return double('receiver') + @delegator.send(@to).stub(method).and_return :called + @delegator.send(@method) == :called + end + + description do + "delegate :#{@method} to its #{@to}#{@prefix ? ' with prefix' : ''}" + end + + failure_message_for_should do |text| + "expected #{@delegator} to delegate :#{@method} to its #{@to}#{@prefix ? ' with prefix' : ''}" + end + + failure_message_for_should_not 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 \ No newline at end of file