-
-
Notifications
You must be signed in to change notification settings - Fork 454
/
deny_access_matcher.rb
115 lines (101 loc) · 3.23 KB
/
deny_access_matcher.rb
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
module Clearance
module Testing
# Provides matchers to be used in your controller specs.
# These are typically exposed to your controller specs by
# requiring `clearance/rspec` or `clearance/test_unit` as
# appropriate in your `rails_helper.rb` or `test_helper.rb`
# files.
module Matchers
# The `deny_access` matcher is used to assert that a
# request is denied access by clearance.
# @option opts [String] :flash The expected flash alert message. Defaults
# to nil, which means the flash will not be checked.
# @option opts [String] :redirect The expected redirect url. Defaults to
# `'/'` if signed in or the `sign_in_url` if signed out.
#
# class PostsController < ActionController::Base
# before_action :require_login
#
# def index
# @posts = Post.all
# end
# end
#
# describe PostsController do
# describe "#index" do
# it "denies access to users not signed in" do
# get :index
#
# expect(controller).to deny_access
# end
# end
# end
def deny_access(opts = {})
DenyAccessMatcher.new(self, opts)
end
# @api private
class DenyAccessMatcher
attr_reader :failure_message, :failure_message_when_negated
def initialize(context, opts)
@context = context
@flash = opts[:flash]
@url = opts[:redirect]
@failure_message = ''
@failure_message_when_negated = ''
end
def description
'deny access'
end
def matches?(controller)
@controller = controller
sets_the_flash? && redirects_to_url?
end
def failure_message_for_should
failure_message
end
def failure_message_for_should_not
failure_message_when_negated
end
private
def denied_access_url
if clearance_session.signed_in?
Clearance.configuration.redirect_url
else
@controller.sign_in_url
end
end
def clearance_session
@controller.request.env[:clearance]
end
def flash_alert_value
@controller.flash[:alert]
end
def redirects_to_url?
@url ||= denied_access_url
begin
@context.send(:assert_redirected_to, @url)
@failure_message_when_negated <<
"Didn't expect to redirect to #{@url}."
true
rescue ::Minitest::Assertion, ::Test::Unit::AssertionFailedError
@failure_message << "Expected to redirect to #{@url} but did not."
false
end
end
def sets_the_flash?
if @flash.blank?
true
elsif flash_alert_value == @flash
@failure_message_when_negated <<
"Didn't expect to set the flash to #{@flash}"
true
else
@failure_message << "Expected the flash to be set to #{@flash} "\
"but was #{flash_alert_value}"
false
end
end
end
end
end
end