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
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值