|
| 1 | +require 'minitest/autorun' |
| 2 | +require 'rack/test' |
| 3 | +require 'grape/cancan' |
| 4 | +require 'cancancan' |
| 5 | + |
| 6 | +User = Class.new |
| 7 | + |
| 8 | +class Ability |
| 9 | + include CanCan::Ability |
| 10 | + |
| 11 | + def initialize(user) |
| 12 | + can :read, User |
| 13 | + cannot :love, User |
| 14 | + end |
| 15 | +end |
| 16 | + |
| 17 | +class API < Grape::API |
| 18 | + authorize_routes! |
| 19 | + helpers { define_method(:current_user) { User.new } } |
| 20 | + get('/can') { can? :love, current_user } |
| 21 | + get('/cannot') { cannot? :read, current_user } |
| 22 | + get('/authorize_option', authorize: [:read, User]) |
| 23 | + get('/authorize_option_fail', authorize: [:love, User]) |
| 24 | + get('/authorize_explicit') { authorize! :read, current_user } |
| 25 | + get('/authorize_explicit_fail') { authorize! :love, current_user } |
| 26 | +end |
| 27 | + |
| 28 | +class GrapeCancanTest < Minitest::Test |
| 29 | + include Rack::Test::Methods |
| 30 | + |
| 31 | + def app |
| 32 | + API |
| 33 | + end |
| 34 | + |
| 35 | + def test_can |
| 36 | + get '/can' |
| 37 | + assert_equal 'false', last_response.body |
| 38 | + end |
| 39 | + |
| 40 | + def test_cannot |
| 41 | + get '/cannot' |
| 42 | + assert_equal 'false', last_response.body |
| 43 | + end |
| 44 | + |
| 45 | + def test_authorize_option |
| 46 | + get '/authorize_option' |
| 47 | + assert_equal 200, last_response.status |
| 48 | + end |
| 49 | + |
| 50 | + def test_authorize_option_failure |
| 51 | + assert_raises CanCan::AccessDenied do |
| 52 | + get '/authorize_option_fail' |
| 53 | + end |
| 54 | + end |
| 55 | + |
| 56 | + def test_authorize_explicit |
| 57 | + get '/authorize_explicit' |
| 58 | + assert_equal 200, last_response.status |
| 59 | + end |
| 60 | + |
| 61 | + def test_authorize_explicit_failure |
| 62 | + assert_raises CanCan::AccessDenied do |
| 63 | + get '/authorize_explicit_fail' |
| 64 | + end |
| 65 | + end |
| 66 | +end |
0 commit comments