Rails Pundit mini test assert_response Pundit::NotAuthorizedError

妖精的绣舞 提交于 2019-12-12 04:28:08

问题


I am using Rails 5 API, Pundit and all is going well. I am trying to test this specific case where if you're not the resource owner, you should not be able to view that user's info.

So I got a few user fixture sample data, Sarah and Jim are two of them.

I got this test case here:

test "user show - cannot show other user's info" do
  get user_path(@sarah), headers: user_authenticated_header(@jim)
  assert_raises(Pundit::NotAuthorizedError)
end

I ran my test, all the other ones passed, except this one which says:

Error:
UsersControllerTest#test_user_show_-_cannot_show_other_user's_info:
Pundit::NotAuthorizedError: not allowed to show?

Am I writing the assert_raise exception correctly? Why is my test not passing? It seems like once the error is raised, the next line in my test is not ran anymore.


回答1:


I hate it when I keep answering my own questions...far out :(

After more searching, it turns out it's like this:

test "user show - cannot show other user's info" do
  assert_raises(Pundit::NotAuthorizedError) {
    get user_path(@sarah), headers: user_authenticated_header(@jim)
  }
end

I found the answer after finding this:

http://apidock.com/ruby/Test/Unit/Assertions/assert_raise

assert_raises takes an error type, in my case Pundit::NotAuthorizedError and a block of code to assert the error will be raised for.

In other words:

assert_raises(ExceptionType) {
  // my code to execute that will cause the error to happen
}

My other searches usually turns up RSpec testing syntax. Leaving this answer here for future Rails developers using Mini Test like me :D



来源:https://stackoverflow.com/questions/40690056/rails-pundit-mini-test-assert-response-punditnotauthorizederror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!