Rails Pundit mini测试assert_response Pundit :: NotAuthorizedError

时间:2016-11-19 06:51:03

标签: ruby-on-rails minitest pundit

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

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

我在这里得到了这个测试用例:

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

我跑了我的测试,所有其他的都通过了,除了这个说:

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

我是否正确编写了assert_raise异常?为什么我的考试没有通过?似乎一旦出现错误,我的测试中的下一行就不再运行了。

1 个答案:

答案 0 :(得分:2)

当我不断回答自己的问题时,我讨厌它......远远地说:(

经过更多搜索后,事实证明是这样的:

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

我找到答案后找到了答案:

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

assert_raises采用错误类型,在我的情况下为Pundit::NotAuthorizedError,并且会引发一个断言错误的代码块。

换句话说:

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

我的其他搜索通常会出现RSpec测试语法。将此答案留给未来的Rails开发人员使用像我这样的迷你测试:D