Search code examples
ruby-on-railsfunctional-testing

Is it ok to use Post.first instead of assigns(:post) in a controller test?


In a rails (4.2.x) app, in controller tests, I see a lot of examples where they use assigns(:post), where I could use Post.first or Post.find_by(title: 'foo') instead. I don't understand the need for assigns at all. (I heard that assigns will be deprecated in rails 5, but until then, is it ok to use the object directly?) Is it wrong to do this, for example:

assert_redirected_to(post_path(Post.first))

instead of:

assert_redirected_to(post_path(assigns(:post))

Solution

  • assigns(:post) is just a refer to an action variable @post. Action can look like:

    @post = Post.first
    

    or:

    @post = Post.find_by(title: 'foo')
    

    In test through assigns(:post) you can get a @post variable from the controller action.