[rspec-users] Controller spec: testing that scope is set

Michael Schuerig michael at schuerig.de
Mon Apr 20 16:26:14 EDT 2009


On Monday 20 April 2009, Pat Maddox wrote:
> In a functional test, create some records that will be in the scope
> and some that will be out of the scope, hit the page and make sure
> you only see the ones that you want.  I would either do this with
> cucumber, or write a controller spec and verify that only certain
> records show in the the assigns var.  Either way you're going to have
> to hit the db because obviously the scope affects the db queries.

Yes, and that feels a bit like cheating.

> This is why you'd typically like to keep that stuff in the model.

I agree on the typically, but disagree specifically.

I've tried my way into rspec, see below, but got stuck at the point 
where I'd have to get hold of the model class.

Michael


require 'spec/mocks/message_expectation'

module Spec #:nodoc:
  module Mocks #:nodoc:

    class ScopeExpectation
      def initialize(args)
        @args = args
      end
      def scope_matches?
        # here a miracle occurs
        ...
      end
    end
    
    
    module MessageExpectationScopeExtension
      def self.included(base)
        base.send(:alias_method, :matches_without_scope, :matches)
        base.send(:alias_method, :matches, :matches_with_scope)
      end
      def within_scope(*args)
        @scope_expectation = ScopeExpectation.new(args)
        self
      end
      def matches_with_scope(*args, &block)
        matches_without_scope(*args, &block) &&
          (!@scope_expectation || @scope_expectation.scope_matches?)
      end
    end
  end
end

Spec::Mocks::MessageExpectation.class_eval do
  include Spec::Mocks::MessageExpectationScopeExtension
end

-- 
Michael Schuerig
mailto:michael at schuerig.de
http://www.schuerig.de/michael/



More information about the rspec-users mailing list