Mostly programming and parenting, and not a hint of sarcasm
Posts tagged assert
It Should Include Only One Of – An RSpec Matcher
0256 days
by Chris Bloom
in Code Snippets
I know RSpec tests should typically be implementation/data agnostic, but I ran into a situation in a unit test where I needed to make sure that the results of a query returned only one of the two records that were created during the setup but without knowing which record that would be ahead of time. This was due to the fact that the scoped finder returned a random record. So, I wrote a little matcher that lets me assert that a given array contains only one of a set of specified elements.
# Inspired by http://blog.nicksieger.com/articles/2011/01/20/rspec-2-matcher-funRSpec::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}" endendYou can use it like so:
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) endend
Recent Comments