Skip to content

Commit

Permalink
add with option to rspec matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
Kris Leech committed Aug 15, 2014
1 parent 58d3f52 commit 605cc6c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
38 changes: 28 additions & 10 deletions lib/wisper/rspec/matchers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,26 @@ def respond_to?(method_name)
end

def method_missing(method_name, *args, &block)
@broadcast_events << method_name.to_s
@broadcast_events << Event.new(method_name.to_s, args)
end

def broadcast?(event_name)
@broadcast_events.include?(event_name.to_s)
def broadcast?(event_name, args = nil)
if args.nil?
!!@broadcast_events.find { |event| event.name == event_name.to_s }
else
@broadcast_events.include?(Event.new(event_name.to_s, args))
end
end

# TODO: make === equality string/symbol agnostic for name
class Event < Struct.new(:name, :args); end
end

module BroadcastMatcher
class Matcher
def initialize(event)
@event = event
def initialize(event_name, options)
@event = event_name
@args = options.key?(:with) ? Array(options[:with]) : nil
end

def supports_block_expectations?
Expand All @@ -37,20 +45,30 @@ def matches?(block)
block.call
end

event_recorder.broadcast?(@event)
event_recorder.broadcast?(@event, @args)
end

def failure_message
"expected publisher to broadcast #{@event} event"
message = "expected publisher to broadcast #{@event} event"
message << " with arguments #{@args.join(', ')}" if with_args?
message
end

def failure_message_when_negated
"expected publisher not to broadcast #{@event} event"
message = "expected publisher not to broadcast #{@event} event"
message << " with arguments #{@args.join(', ')}" if with_args?
message
end

private

def with_args?
!@args.nil?
end
end

def broadcast(event)
Matcher.new(event)
def broadcast(event_name, options = {})
Matcher.new(event_name, options)
end
end
end
Expand Down
5 changes: 5 additions & 0 deletions spec/lib/wisper/rspec/matchers_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,9 @@
publisher = publisher_class.new
expect { publisher }.not_to broadcast(:foobar)
end

it 'passes when publisher broadcasts with given arguments' do
publisher = publisher_class.new
expect { publisher.send(:broadcast, :foobar, :arg1) }.to broadcast(:foobar, with: :arg1)
end
end

0 comments on commit 605cc6c

Please sign in to comment.