RSpec - 测试强参数 ActionController::ParameterMissing [英] RSpec - Testing Strong Parameters ActionController::ParameterMissing

查看:33
本文介绍了RSpec - 测试强参数 ActionController::ParameterMissing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试某个操作是否引发了 ActionController::ParameterMissing 异常?

How can one test if a certain action raises an ActionController::ParameterMissing exception?

例如:

it "raises an exception" do
  post :create, {}
  expect(response).to raise ActionController::ParameterMissing
end

以上似乎不起作用,它会因 ActionController::ParameterMissing 异常而导致测试失败.

The above does not seem to work, it will fail the test with the ActionController::ParameterMissing exception.

推荐答案

使用 expect 块语法使用 raise_error 匹配器:

Use the expect block syntax using the raise_error matcher:

it "raises an exception" do
  expect{ post(:create, {}) }.to raise_error ActionController::ParameterMissing
end

您的代码不起作用的原因是 post(:create, {}) 引发了异常.这发生在 expect(response).to ... 代码执行之前.由于 #post 消息不在 begin...end 块中,引发的异常被传递给 RSpec 测试失败.

The reason that your code doesn't work is that post(:create, {}) raises the exception. This happens before the expect(response).to ... code gets executes. Since the #post message is not in a begin...end block, the raised exception is passed up to RSpec failing the test.

这篇关于RSpec - 测试强参数 ActionController::ParameterMissing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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