Skip to content

Instantly share code, notes, and snippets.

@sukima
Created October 6, 2010 15:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sukima/613522 to your computer and use it in GitHub Desktop.
Save sukima/613522 to your computer and use it in GitHub Desktop.
Possible custom shoulda matcher
require 'test_helper'
class CalendarControllerTest < ActionController::TestCase
should route(:get, "/calendar").to(:action => :index)
should route(:get, "/calendar/events").to(:action => :events)
# Error:
# functional/calendar_controller_test.rb:9: undefined local variable or
# method `require_logged_in' for CalendarControllerTest:Class (NameError)
should require_logged_in
should require_logged_in.for(:events)
end
module Shoulda
module SimNotify
module Matchers
def require_logged_in(method = :get)
RequireLoggedInMatcher.new(method)
end
def require_admin(method = :get)
RequireAdminMatcher.new(method)
end
class RequireLoggedInMatcher
def initialize(method = :get)
@check_action = :index
@use_method = method
end
def for(action)
@check_action = action
self
end
def matches?(subject)
if @use_method == :post
post @check_action
else
get @check_action
end
RedirectToMatcher.new(login_path).matcher?
end
def description
"require user to log in for #{@check_action.to_s} action"
end
end
class RequireAdminMatcher
def initialize(method = :get)
@check_action = :index
@use_method = method
end
def for(action)
@check_action = action
self
end
def matcher?
if @use_method == :post
post @check_action
else
get @check_action
end
SetTheFlashMatcher.new.to(I18n.translate(:admin_required)).matches?
end
def description
"require administrator access for #{@check_action.to_s} action"
end
end
end
end
end
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require 'authlogic/test_case'
require 'shoulda_matchers/require_logged_in.rb'
class ActiveSupport::TestCase
include Authlogic::TestCase
include Shoulda::SimNotify::Matchers
extend Shoulda::SimNotify::Matchers
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment