Rails Pundit 迷你测试 assert_response Pundit::NotAuthorizedError

Rails Pundit mini test assert_response Pundit::NotAuthorizedError

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

所以我得到了一些用户fixture样本数据,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 异常?为什么我的测试没有通过?似乎一旦出现错误,我测试的下一行就不再是 运行。

我讨厌自己不断回答自己的问题...太过分了:(

多方查找,原来是这样的:

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 测试语法。将此答案留给未来像我一样使用 Mini Test 的 Rails 开发人员 :D