问题
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