您如何在 Rails 测试中指定 POST 参数? [英] How do you specify POST params in a Rails test?

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

问题描述

使用 Test::Unit 和 Shoulda.尝试测试 Users.create.我的理解是 Rails 表单为这样的对象发送参数:

Working with Test::Unit and Shoulda. Trying to test Users.create. My understanding is that Rails forms send params for an object like this:

user[email]

在您的操作中哪个会变成哈希,对吗?

Which turns into hash in your action, right?

params[:user][:email]

好的,所以在我的测试中我已经尝试过...

OK, so in my test I've tried...

setup { post :create, :post => { 'user[email]' => 'invalid@abc' } }

setup { post :create, :post => { :user => { :email => 'abc@abcd' } } }

在这两种情况下,在我的操作中,params[:user] 为零.

In both cases, over in my action, params[:user] is nil.

推荐答案

post :create, :user => { :email => 'foo@bar.com' }

get、post、put、delete所有测试方法的一般形式如下:

The general form for all the test methods of get, post, put, delete are as follows:

def post(action_name, params_hash = {}, session_hash = {})

在测试中,params 散列被直接发送到您的控制器操作的 params 中,没有任何类型的转换.即使进行集成测试,您也确实不需要测试这个字符串到 params 的翻译,因为 Rails 框架测试很好地涵盖了它.此外,所有需要参数的测试方法都以这种方式接受散列,无需抱怨,让您轻松完成.

And in tests, the params hash gets directly sent into params of your controller action with no translation of any sort. Even doing integration testing you really shouldnt need to test this string to params translation as its covered very well by the rails framework tests. Plus all testing methods that need params accept a hash in this manner without complaint making things easy for you.

这篇关于您如何在 Rails 测试中指定 POST 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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