mardi 4 août 2015

Testing a Rails password change form

I'm new to rails, and testing is still a bit mysterious to me. I searched unsuccessfully for a way to test forms without adding gems. Here's what I'm trying to do.

My form has old_password, new_password, and confirm_password fields.

<%= form_for @user, :url => "change_password" do |f| %>
    <%= f.label :Current_Password %>
    <%= f.password_field :old_password, class: 'form-control' %>
    <%= f.label :New_Password %>
    <%= f.password_field :new_password, class: 'form-control' %>
    <%= f.label :Confirm_Password %>
    <%= f.password_field :password_confirmation, class: 'form-control' %>
    <%= f.submit "Change Password", class: "btn btn-primary" %>
<% end %>

My routes

 # Users
  resources "users"

  patch 'users/:id/change_password' => 'users#change_password'

My users controller action

  def change_password
    # Change password.
    @user = User.find(params[:id])
    if @user and @user.authenticate(params[:user][:old_password])
      if params[:user][:new_password] == params[:user][:password_confirmation]
        @user.update_attribute(:password_digest, 
            User.digest(params[:user][:new_password]))
        flash[:success] = "Password changed sucesfully."
        redirect_to @user
      else
        flash.now[:danger] = "Password and confirmation do not match."
        render 'edit'
      end
    else
      flash.now[:danger] = "Incorrect password."
      render 'edit'
    end
  end

My test. It is very similar to the test from the Rails Tutorial. This is the piece I don't understand.

  test "password change wrong password" do
    get edit_user_path(@user)
    assert_template 'users/edit'

    # Submit wrong password.
    patch user_path(@user), user: { old_password: "invalid",
                                    new_password:  "foobar11",
                                    password_confirmation: "foobar11" }

    # Flash not empty.
    assert_not flash.empty?

    # Redirected to edit page.
    assert_template 'users/edit'

    # Password not changed in database.

  end

The test fails on assert_template 'users/edit'

expecting <"users/edit"> but rendering with <[]>

Aucun commentaire:

Enregistrer un commentaire