Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@thedanielhanke
Created March 24, 2016 10:15
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 thedanielhanke/0560e615155f0f829802 to your computer and use it in GitHub Desktop.
Save thedanielhanke/0560e615155f0f829802 to your computer and use it in GitHub Desktop.
# RSpec matcher to spec delegations.
#
# Usage:
#
# describe Post do
# it 'delegates name to Author' do
# expect subject.to delegate(:name).to(:author).with_prefix # post.author_name
# end
# it 'delegates month to creation date' do
# expect subject.to delegate(:month).to :created_at
# end
# it { delegates(:year).to :created_at }
# end
#
# describe Toolbox
# it { delegates(:api_endpoint).to Application::Config }
# end
RSpec::Matchers.alias_matcher :delegates, :delegate
RSpec::Matchers.define :delegate do |method|
match do |delegator|
@method = @prefix ? :"#{@to}_#{method}" : method
unless delegator.respond_to? @method
fail "#{delegator} does not respond to #{@to}!"
end
@target_name = "#{@to}#{@prefix ? ' with prefix' : ''}"
receiver = @to.is_a?(Symbol) ? double(:receiver) : @to
expect(receiver).to receive(method) { :called }
if @to.is_a? Symbol
expect(delegator).to receive(@to) { receiver }
end
delegator.send(@method) == :called
end
chain(:to) { |receiver| @to = receiver }
chain(:with_prefix) { @prefix = true }
description do |actual|
"#{actual} delegates :#{@method} to #{@target}"
end
failure_message do |actual|
"expected #{actual} to delegate :#{@method} to #{@target}"
end
failure_message_when_negated do |actual|
"expected #{actual} not to delegate :#{@method} to #{@target}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment