Rails Pundit迷你测试assert_response Pundit :: NotAuthorizedError [英] Rails Pundit mini test assert_response Pundit::NotAuthorizedError

查看:128
本文介绍了Rails Pundit迷你测试assert_response Pundit :: NotAuthorizedError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Rails 5 API,Pundit,一切进展顺利.我正在尝试测试这种特定情况,在这种情况下,如果您不是资源所有者,则您将无法查看该用户的信息.

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.

所以我得到了一些用户夹具样本数据,Sarah和Jim是其中两个.

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?

我是否正确编写assert_raise异常?为什么我的考试不及格?似乎一旦引发错误,测试中的下一行就不再运行.

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.

推荐答案

当我继续回答自己的问题时,我讨厌它...很远:(

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采用错误类型,在我的情况下为Pundit::NotAuthorizedError,将引发用于断言该错误的代码块.

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

换句话说:

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

我的其他搜索通常会显示RSpec测试语法.将此答案留给将来像我这样使用Mini Test的Rails开发人员使用:D

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

这篇关于Rails Pundit迷你测试assert_response Pundit :: NotAuthorizedError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆