Reputation: 38410
I have a controller method that I'm annotating like so:
@Secured(['ROLE_ADMIN'])
def save() {
... // code ommitted
}
I'm trying to write a unit test to verify that only the admin user can hit the URL:
def "Only the admin user should be able to invoke save"() {
given:
def user = createNonAdminUser() // let's pretend this method exists
controller.springSecurityService = Mock(SpringSecurityService)
controller.springSecurityService.currentUser >> user
when:
controller.save()
then:
view ==~ 'accessdenied'
}
However, the view returned is the save
view and not the access denied view. It looks like it's bypassing the @Secured
annotation altogether. Is there a way to test @Secured
annotations from either a unit test or integration test?
Upvotes: 4
Views: 1186
Reputation: 50265
You would need to login the user before calling controller save if you are not doing it already in createNonAdminUser()
.
SpringSecurityUtils.reauthenticate username, password
Possibly related to this question.
Upvotes: 0
Reputation: 11307
Try this:
SpringSecurityUtils.doWithAuth('superuser') {
controller.save()
}
http://greybeardedgeek.net/2011/05/13/testing-grails-controllers-with-spock/
Upvotes: 2