Search code examples
ruby-on-railsrubyunit-testingfunctional-testing

How would I setup a functional test for this in Rails?


Ok so I have made a login action but I'm a bit confused on how I would setup a functional or unit test for this. Would it be something like send a username and password from on of my fixtures and check if the session[:user_id] is nil?

Thanks in advance :)

    #POST /sessions
  def create
    user = User.authenticate(params[:email],params[:password])
    if user
      session[:user_id] = user.id
      redirect_to root_path, :notice => "Logged in successfully!"
    else
      flash.now.alert = "Invalid username/password"
      render "new"
    end
  end

Solution

  • Logically, there are several tests that you can make:

    1. Send an invalid email (for a user that you haven't created). You can check for the flash, and you can check that new has been rendered.
    2. Send an invalid password (for a user that you have created). Check for flash, and that new has been rendered.
    3. Send a valid email/password combo (for a user that you have rendered). Check that you have been properly redirected, and that the user_id is present in the session variables.

    Assuming that you are using the standard rails test framework, this would be placed under the functional tests for your session controller. You'd test for redirects and renders by doing things like:

    assert_template "new"
    

    and

    assert_redirected_to root_path
    

    More info here (especially about the hashes that are available after you've done a post):

    http://guides.rubyonrails.org/testing.html#functional-tests-for-your-controllers