rspec 测试,在我的情况下如何获取 id? [英] rspec test, how to get the id in my case?

查看:42
本文介绍了rspec 测试,在我的情况下如何获取 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对我的控制器进行了 rsepc 测试,在我的测试中,我有以下代码片段:

I have a rsepc test for my controller, in my test, I have the following code snippet:

...
params= {SOME PARAMETERS}
post :create, params

上面的代码在我的控制器中测试了 create 方法,create 方法创建了一个实例对象并将其保存到数据库中.

the above code test the create method in my controller, the create method create a instance object and save it into database.

现在的问题是如何获取数据库中创建的实例对象的id?

Now the problem is how can I get the id of the created instance object in database?

好像(我不确定)我需要查询这个对象的测试数据库,如何查询?(PS:我知道有Factory可用于创建对象实例,但这是对控制器的测试,使用Factory会失去测试控制器创建方法的目的.所以,请不要建议我使用工厂)

It seems (I am not sure) I need to query the test database for this object, how to query? (PS: I know there is Factory can be used to create object instance, BUT this is a test for controller, use Factory will loose the purpose of testing controller's create method. So, please do not advice me to use Factory)

我想知道如何根据我的代码获取我创建的对象实例的 id?谢谢:)

I would like to know how to get the id of my created object instance based on my code? Thank you:)

推荐答案

如果您在控制器中使用类似的东西分配对象

If you assign the object in your controller with something like

@object = Object.new(params[:object]

然后它可以使用assigns方法使用,因此您可以执行以下操作:

then it'll be available using the assigns method, so you could do the following:

assigns[:object].id

它会返回id,假设它保存成功.

and it will return the id, assuming it saved successfully.

-- 编辑 --

对于 RSpec 2,它似乎分配的是一个方法调用,因此您可以像这样提供属性

with RSpec 2 it seems assigns is a method call, so you provide the attribute like so

assigns(:object)

代替旧的类似哈希的行为

instead of the old hash-like behaviour

这篇关于rspec 测试,在我的情况下如何获取 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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