Created
September 21, 2008 23:18
-
-
Save sbecker/11918 to your computer and use it in GitHub Desktop.
RSpec matcher for have_named_scope, extended to allow testing of procs - original at http://www.evolve.st/articles/11-testing-named-scope-with-rspec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Image < ActiveRecord::Base | |
named_scope :allowed_for, lambda { |account| { :conditions => ["aws_is_public = ? OR account_id = ?", true, account.id] }} | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
describe Image do | |
describe "named scopes" do | |
it "should have a 'allowed_for' named scope where either 'aws_is_public' is true or 'account_id' matches the id for the passed in account" do | |
Image.should have_named_scope(:allowed_for, | |
lambda { |account| { :conditions => ["aws_is_public = ? OR account_id = ?", true, account.id] }}, | |
mock('Account', :id => 1)) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module NamedScopeSpecHelper | |
class HaveNamedScope #:nodoc: | |
def initialize(scope_name, options, proc_args=nil) | |
@scope_name = scope_name.to_s | |
@options = options | |
@proc_args = proc_args | |
end | |
def matches?(klass) | |
@klass = klass | |
if @options.class == Proc | |
@klass.send(@scope_name, *@proc_args).proxy_options.should === @options.call(*@proc_args) | |
else | |
@klass.send(@scope_name).proxy_options.should === @options | |
end | |
true | |
end | |
def failure_message | |
"expected #{@klass} to define named scope '#{@scope_name}' with options #{@options.inspect}, but it didn't" | |
end | |
def negative_failure_message | |
"expected #{@klass} to not define named scope '#{@scope_name}' with options #{@options.inspect}, but it did" | |
end | |
end | |
def have_named_scope(scope_name, options, proc_args=nil) | |
HaveNamedScope.new(scope_name, options, proc_args) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Default spec_helper code left out for clarity | |
include NamedScopeSpecHelper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment