2012-09-18 43 views
1

所以我正在通過Ruby on Rails 3教程。我目前在7.1.3節使用工廠測試用戶顯示頁面。Ruby on Rails 3教程gravatar_for測試錯誤

該代碼正在工作,並拉扯適當的gravatar圖像,但是當我運行我的測試時,我不斷收到錯誤。

以下是錯誤:

Failure/Error: before { visit user_path(user) } 
    ActionView::Template::Error: 
     undefined method `downcase' for nil:NilClass 

下面是從show.html.erb文件中的代碼:

<% provide(:title, @user.name) %> 
<h1> 
    <%= gravatar_for @user %> 
    <%= @user.name %> 
</h1> 
<%= @user.name %>, <%= @user.email %> 

下面是從users_helper.rb文件中的代碼:

module UsersHelper 
    # Returns the Gravatar (http://gravatar.com/) for the given user. 
    def gravatar_for(user) 
    gravatar_id = Digest::MD5::hexdigest(user.email.downcase) 
    gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}" 
    image_tag(gravatar_url, alt: user.name, class: "gravatar") 
    end 
end 

以下是來自factories.rb文件的代碼:

FactoryGirl.define do 
    factory :user do 
    name "Curtis Test" 
    email "[email protected]" 
    password "foobar" 
    password_confirmation "foobar" 
    end 
end 

下面是測試文件的代碼user_pages_spec.rb

require 'spec_helper' 

describe "User Pages" do 
    subject { page } 

    describe "profile page" do 
    let(:user) { FactoryGirl.create(:user) } 

    before { visit user_path(user) } 
    it { should have_selector('h1', text: user.name) } 
    it { should have_selector('title', text: user.name) } 
    end 

    describe "signup page" do 
    before { visit signup_path } 
    it { should have_selector('title', text: full_title('Sign Up')) } 
    end 
end 
+0

如果我將gravatar_for代碼替換爲只返回user.email.downcase,它就可以工作,所以我很困惑,爲什麼我得到錯誤 – covard

回答

1

我發現我的問題。它與FactoryGirl無關。這個問題在我的用戶模型(user.rb),這是導致該問題的路線是

before_save { |user| user.email = user.email.downcase! } 

的downcase是造成的電子郵件地址後,一聲巨響,因爲downcase返回保存爲無!是零。一旦我刪除了,並使該行看起來像下面,它工作得很好。

before_save { |user| user.email = user.email.downcase } 

我發現它的方式是在測試環境中加載rails控制檯並嘗試創建一個新用戶。我注意到,一切都很好,但電子郵件爲空。

相關問題