Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created January 7, 2010 19:18
Show Gist options
  • Save ashmoran/271475 to your computer and use it in GitHub Desktop.
Save ashmoran/271475 to your computer and use it in GitHub Desktop.
Spec::Matchers.define :include_all_at_least_times do |expected_elements, times|
match do |target_collection|
@elements_seen = expected_elements.inject({ }) { |hash, element| hash[element] = 0; hash }
target_collection.each do |element|
@elements_seen[element] += 1 if @elements_seen.has_key?(element)
end
@elements_seen.values.all? { |count| count >= times.to_i }
end
failure_message_for_should do |target_collection|
"Expected #{target_collection.inspect} to include #{expected_elements.inspect} at least #{times} got the following counts: #{@elements_seen.inspect}"
end
end
Spec::Matchers.define :include_all_once do |expected_elements|
match do |target_collection|
@missing = []
@non_unique = 0
expected_elements.each do |expected_element|
elements_in_target_collection = target_collection.select { |target| target == expected_element }
@missing << expected_element if elements_in_target_collection.empty?
@non_unique += 1 if elements_in_target_collection.size > 1
end
@missing.empty? && @non_unique == 0
end
failure_message_for_should do |target_collection|
if @missing.empty?
"Expected #{target_collection.inspect} to include #{expected_elements.inspect} just once but saw #{@non_unique} non-unique elements."
else
"Expected #{target_collection.inspect} to include #{expected_elements.inspect} just once but was missing #{@missing.inspect}"
end
end
end
Spec::Matchers.define :include_any do |expected_elements|
match do |target_collection|
@included = []
expected_elements.each do |expected_element|
@included << expected_element if target_collection.include?(expected_element)
end
[email protected]?
end
failure_message_for_should_not do |target_collection|
"Expected #{target_collection.inspect} not to include any of #{expected_elements.inspect} but saw #{@included.inspect}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment