start from TDD!!!
1. require 'spec_helper'
describe SessionsController do render_views . . . describe "POST 'create'" do describe "invalid signin" do before(:each) do @attr = { :email => "[email protected]", :password => "invalid" } end it "should re-render the new page" do post :create, :session => @attr response.should render_template('new') end it "should have the right title" do post :create, :session => @attr response.should have_selector("title", :content => "Sign in") end it "should have a flash.now message" do post :create, :session => @attr flash.now[:error].should =~ /invalid/i end end end end
what 's flash.now[:error] and flash[:error]
we will explain it in a short article later.
2. let's write code to make the test pass!
def create user = User.authenticate(params[:session][:email], params[:session][:password]) if user.nil? flash.now[:error] = "Invalid email/password combination." @title = "Sign in" render 'new' else # Sign the user in and redirect to the user's show page. end end
a. you may wondering, why we use user instead of @user,
because the user object will never be used again, so it is not needed to use a instance var, which will take more resource.
b. remember, render will just render the page, won't execute the action!!!
c. when using render, pls use flash.now[:error] = ""
when using redirect, pls use flash[:error] = ""
d. since we don't have models here, so we can't use something like @user.errors.full_messages to display errors, so we use flash.now[:error] to store the error messages.
ok, done, the test passed.