Skip to content

Instantly share code, notes, and snippets.

@cee-dub
Forked from zbrock/gist:615961
Created October 13, 2010 06:47
Show Gist options
  • Select an option

  • Save cee-dub/623589 to your computer and use it in GitHub Desktop.

Select an option

Save cee-dub/623589 to your computer and use it in GitHub Desktop.
def should_be_a_subset(all_objects, constrained_scope, &condition)
flunk "Your superset is empty" if all_objects.empty?
flunk "Your constrained set is empty" if constrained_scope.empty?
objects_for_which_condition_is_true, objects_for_which_condition_is_false = all_objects.partition(&condition)
flunk "Your test condition did not select any items" if objects_for_which_condition_is_true.empty?
flunk "Your test condition did not exclude any items" if objects_for_which_condition_is_false.empty?
constrained_scope.map(&:id).sort.should == objects_for_which_condition_is_true.map(&:id).sort
(all_objects.map(&:id) - constrained_scope.map(&:id)).should == objects_for_which_condition_is_false.map(&:id)
end
@readysetawesome
Copy link

Examples become even more readable if you make a custom matcher out of this:

RSpec::Matchers.define :be_a_subset_of do |superset, condition|
  match do |subset|
    should_be_a_subset(superset, subset, &condition)
  end
end

usage:

User.registered.should be_a_subset_of(User.all, lambda {|u| !u.registered_at.nil? })

@seako
Copy link

seako commented Nov 24, 2013

i was inspired by this post to make an analogous matcher for ordering scopes

https://gist.github.com/seako/7632799

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment