如何使用 Rspec 测试强参数? [英] How to test strong params with Rspec?

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

问题描述

使用 Rspec 在 Rails 控制器中测试强参数过滤的实际策略是什么?(除了 shoulda 匹配器)如何编写失败的测试然后让它变成绿色?

What is the actual strategy to test strong params filtering in Rails controller with Rspec? (Except shoulda matchers) How to write failing test and then make it green?

推荐答案

使用预期和所有(不满足的)参数创建 2 个散列.然后将所有参数传递给操作并检查您的对象模型是否仅接收预期的参数.如果您不使用强参数过滤器,则不会.比给参数添加权限并再次检查测试.

Create 2 hashes with expected and all (with unsatisfied) parameters. Then pass all params to action and check that you object model receiving only expected params. It will not if you are not using strong parameter filters. Than add permissions to params and check test again.

例如:

# action
def create
  User.create(params)
end

# spec
it 'creates a user' do
  expect_any_instance_of(User).to receive(:create).
    with({name: 'Sideshow Bob'}.with_indifferent_access)
  post :create, user: 
    { first_name: 'Sideshow', last_name: 'Bob', name: 'Sideshow Bob' }
end

将所有参数传递给用户,测试将失败.当你过滤它们时:

will pass all params to User and test will fail. And when you filter them:

def user_params
  params.require(:user).permit(:name)
end

并使用 User.create(user_params) 更改操作,测试将通过.

and change action with User.create(user_params), test will pass.

这篇关于如何使用 Rspec 测试强参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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