rspec test, how to get the id in my case?

那年仲夏 提交于 2019-12-08 04:54:55

问题


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

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

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

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

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)

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


回答1:


If you assign the object in your controller with something like

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

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

assigns[:object].id

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

-- edit --

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



来源:https://stackoverflow.com/questions/5375756/rspec-test-how-to-get-the-id-in-my-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!