Skip to content

Instantly share code, notes, and snippets.

@chrisbloom7
Created June 12, 2011 01:10
Show Gist options
  • Save chrisbloom7/1021142 to your computer and use it in GitHub Desktop.
Save chrisbloom7/1021142 to your computer and use it in GitHub Desktop.
An RSpec2 matcher that asserts that only one of the passed elements is present in the source array
require 'include_only_one_of'
describe "SomeTest" do
it "should return only one wide format promotion if available" do
first_wide_promotion = Factory(:promotion, :brand => @brand, :format => Promotion::FORMATS[:wide])
second_wide_promotion = Factory(:promotion, :brand => @brand, :format => Promotion::FORMATS[:wide])
@brand.featured_promotions.should include_only_one_of(first_wide_promotion, second_wide_promotion)
end
end
# Inspired by http://blog.nicksieger.com/articles/2011/01/20/rspec-2-matcher-fun
RSpec::Matchers.define :include_only_one_of do |*elements|
match do |container|
@included = []
elements.flatten.each do |e|
@included << e if container.include?(e)
end
@included.count == 1
end
failure_message_for_should do |container|
"expected array of #{container.length} elements to include only one member.\n" +
"Found #{@included.flatten.inspect}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment