2011-03-13 115 views
2

我有2個簡單的RSpec測試,我已經寫了一個小型的軌道應用程序,我已經學習軌道。我最初有一個模擬設置爲我的鏈接類,但得到同樣的問題。RSpec控制器測試失敗 - 如何加載模擬數據?

這是我的測試代碼:

require 'spec_helper' 

describe LinksController do 
    render_views 
    before(:each) do 
    link = Link.new 
    link.stub!(:title).and_return("Reddit") 
    link.stub!(:url).and_return("http://www.reddit.com") 
    link.stub!(:created_at).and_return(Time.now) 
    link.stub!(:updated_at).and_return(Time.now) 
    link.stub!(:user_id).and_return("1") 
    link.stub!(:id).and_return("1") 
    link.save 

    user = User.new 
    user.save 
    end 

    it "renders the index view" do 
    get :index 
    response.should render_template('links/index') 
    response.should render_template('shared/_nav') 
    response.should render_template('layouts/application') 
    end 

    it "renders the show view" do 
    get :show, :id => 1 
    response.should render_template('links/show') 
    response.should render_template('shared/_nav') 
    response.should render_template('layouts/application') 
    end 
end 

我是新來的兩個軌和RSpec,不知道我應該怎樣做才能得到這個工作。需要數據時,從LinksController測試此show方法的最佳方法是什麼?我也嘗試了mock_model,但也許我錯誤地使用了它。

你可以看到Github

回答

4

的所有應用程序代碼的問題是,你是磕碰的模型,所以它不是存儲在數據庫中。這意味着當您撥打get :show, :id => 1時,對數據庫的查詢不會返回任何內容,並且測試失敗。如果您想在不使用數據庫的情況下僞造一個響應或一個對象,那麼存根就非常棒,但是如果您依賴於使用數據庫的實際Rails代碼,則不能使用此方法,因爲數據庫中不存在任何內容。爲了解決這個問題,我會完全放棄殘存的模型並實際創建它們。

require 'spec_helper' 

describe LinksController do 
    render_views 
    before(:each) do 
    user = User.create 

    @link = Link.create :title => "Reddit", 
         :url => "http://www.reddit.com", 
         :user => user 
    end 

    it "renders the index view" do 
    get :index 
    response.should render_template('links/index') 
    response.should render_template('shared/_nav') 
    response.should render_template('layouts/application') 
    end 

    it "renders the show view" do 
    get :show, :id => @link.id 
    response.should render_template('links/show') 
    response.should render_template('shared/_nav') 
    response.should render_template('layouts/application') 
    end 
end 

你也應該最終考慮工廠的寶石一樣ShamFactory Girl簡化測試數據的創建。

+0

感謝潘。我仍然有一些故障排除,看起來像我的代碼。我正在顯示在索引頁面和顯示頁面上提交鏈接的用戶的電子郵件地址(未填滿),並且我在nil:NilClass中收到了一個「電子郵件」的Method錯誤消息,因此看起來用戶不在創建。我會更多地考慮這一點,但你的建議似乎已經解決了最初的問題。 – 2011-03-13 19:57:40

+0

這是非常可能的,這可能是因爲簡單地調用User.create不會創建一個有效的用戶。這就是工廠的優點:他們驗證你正在創建一個有效的用戶,你可以在這樣的測試中重新使用它。如果驗證需要用戶收到電子郵件,則可能需要執行類似User.create(:email =>'[email protected]')的操作。 – 2011-03-13 20:00:23

+0

RSpec支持工廠,還是最好從工廠設置工廠女孩? – 2011-03-14 00:43:21