【Rails学习笔记】用户注册的流程

来源:互联网 发布:朗诵配乐知乎 编辑:程序博客网 时间:2024/06/09 21:19



在网站布局中加入debug信息 

<%= debug(params) if Rails.env.development? %>


添加 Gravatar 头像和侧边栏

[html] view plaincopyprint?
  1. <% provide(:title, @user.name) %>  
  2. <h1>  
  3.   <%= gravatar_for @user %>  
  4.   <%= @user.name %>  
  5. </h1>  

然后需要我们自己去定义Gravatar方法 

[html] view plaincopyprint?
  1. module UsersHelper  
  2.   
  3.   # Returns the Gravatar (http://gravatar.com/) for the given user.  
  4.   def gravatar_for(user)  
  5.     gravatar_id = Digest::MD5::hexdigest(user.email.downcase)  
  6.     gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"  
  7.     image_tag(gravatar_url, alt: user.name, class: "gravatar")  
  8.   end  
  9. end  

填写用户注册表单:

[html] view plaincopyprint?
  1. <% provide(:title, 'Sign up') %>  
  2. <h1>Sign up</h1>  
  3.   
  4. <div class="row">  
  5.   <div class="span6 offset3">  
  6.     <%= form_for(@user) do |f| %>  
  7.   
  8.       <%= f.label :name %>  
  9.       <%= f.text_field :name %>  
  10.   
  11.       <%= f.label :email %>  
  12.       <%= f.text_field :email %>  
  13.   
  14.       <%= f.label :password %>  
  15.       <%= f.password_field :password %>  
  16.   
  17.       <%= f.label :password_confirmation, "Confirmation" %>  
  18.       <%= f.password_field :password_confirmation %>  
  19.   
  20.       <%= f.submit "Create my account", class: "btn btn-large btn-primary" %>  
  21.     <% end %>  
  22.   </div>  
  23. </div>  

然后要分别对注册成功和失败两种情况进行测试 

[Ruby] view plaincopyprint?
  1. describe "signup" do  
  2.     before {visit signup_path}  
  3.     let(:submit) {"Create my account"}  
  4.   
  5.     describe "with invalid information" do  
  6.       it "should not create a user" do  
  7.         expect {click_button submit}.not_to change(User, :count)  
  8.   
  9.       end  
  10.     end  
  11.     describe "with valid information" do  
  12.       before do  
  13.         fill_in "Name", with: "Example User"  
  14.         fill_in "Email", with: "user@example.com"  
  15.         fill_in "Password", with: "foobar"  
  16.         fill_in "Confirmation", with: "foobar"  
  17.       end  
  18.       it "should create a user" do  
  19.         expect {click_button submit}.to change(User, :count).by(1)  
  20.       end  
  21.     end  
  22.   
  23.   end  

对应action代码如下:

[ruby] view plaincopyprint?
  1. def create  
  2.         @user = User.new(user_params)  
  3.         if @user.save  
  4.             #  
  5.             flash[:success] = "Welcome to the Sample App!"  
  6.             redirect_to @user  
  7.         else  
  8.             render 'new'  
  9.         end  
  10.     end  





0 0