`
peryt
  • 浏览: 52470 次
  • 来自: ...
最近访客 更多访客>>
社区版块
存档分类
最新评论
  • waiting: 既然都指定了dataType为'script'那就不必特别在b ...
    jQuery

8.3 sign up success

 
阅读更多

Chapter 8.3

this part, we will deal with the case that sign up success.

 

1. start from TDD!!!!

 

 

describe "success" do

      before(:each) do
        @attr = { :name => "New User", :email => "user@example.com",
                  :password => "foobar", :password_confirmation => "foobar" }
      end

      it "should create a user" do
        lambda do
          post :create, :user => @attr
        end.should change(User, :count).by(1)
      end

      it "should redirect to the user show page" do
        post :create, :user => @attr
        response.should redirect_to(user_path(assigns(:user)))
      end    
    end

 there is nothing new:

a. lambda

b. should change(User, :count).by(1)

c. reponse.should redirect_to(user_path(assigns(:user)))

 

assigns is a hash that will be generated on every request, to have all instance variable.

 

2. now it is time the finish the sign up form.

 

 

if @user.save
    redirect_to @user
else
    render :new
end
 

note, we omit user_path in the redirect, this is also a rails convention.

 

3. the flash:

 

the content in flash is a hash, it will only exist for the next request, then disappear, so temporary.

you can iterate the flash content in this way:

 

flash.each do |key, value|

puts "#{key}"

puts "#{value}"

end

 

we will display the flash content in the application layout.

 

<% flash.each do |key, value| %>
  <div class="flash <%= key %>"><%= value %></div>
<% end %> 

 

you can fine this html code is very very ugly, to make it better, we can use the rails helper method

content_tag

 

<%= content_tag :div, value, :class => "flash #{key}" %>

 

for example, if flash[:success] = "Welcome to the sample app!"

 

the html will be:

 

<div class="flash success">Welcome to the Sample App!</div>

 

let's write a test to make sure the key :success appear.

 

 

it "should have a welcome message" do
        post :create, :user => @attr
        flash[:success].should =~ /welcome to the sample app/i
 end

 note, we used 

 

        flash[:success].should =~ /welcome to the sample app/i

 =~ is to see if a regex exist, and the last i indicate case insensitive.

 

for the =~

"jflkdsjlfsdj" =~ /abcd/

if not match, it will return nil

if match, it will return the index of the place starting match. (the index start from 0)

 

the make the test pass, we need to add this line into the controller code's create action:

 

if @user.save
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics