public
Last active

Possible custom shoulda matcher

  • Download Gist
calendar_controller_test.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
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
require_logged_in.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
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
test_helper.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.