2012-11-28 54 views
0

我對使用rails進行測試很新,並且似乎讓自己在測試世界中迷失了方向。我正在測試儀表板控制器,當我從控制器中刪除load_and_authorize_resource行時,所有內容都會通過。我正在使用cancan進行授權。Rspec失敗/錯誤測試設計和cancan

dashboard_controller.rb

def update 
@dashboard = Dashboard.find(params[:id]) 

respond_to do |format| 
    if @dashboard.update_attributes(params[:dashboard]) 
    format.html { redirect_to dashboards_path, notice: 'dashboard was successfully updated.' } 
    format.json { head :no_content } 
    else 
    format.html { render action: "edit" } 
    format.json { render json: @dashboard.errors, status: :unprocessable_entity } 
    end 
end 
end 

dashboard_controller_spec.rb

require 'spec_helper' 

describe DashboardsController do 

    login_user 
    before :each do 
    @dashboard = create(:dashboard, dashboard_name: "My Own Dashboard", id: 1) 
    end 

    describe "GET #index" do 

    it "should have a current_user" do 
     subject.current_user.should_not be_nil 
    end 

    it "renders the :index view" do 
     get :index 
     response.should render_template :index 
    end 

    it "Creates new dashboard" do 
     get :new 
     response.should render_template :new 
    end 

    end 

    describe "Get #edit" do 

    it "assigns dashboard to @dashboard" do 
     get :edit, id: @dashboard 
     assigns(:dashboard).should == @dashboard 
    end 

    it "renders the :edit template" do 
     get :edit, id: @dashboard 
     response.should render_template :edit 
    end 

    end 


end 

我從控制檯

1) DashboardsController Get #edit renders the :edit template 
Failure/Error: response.should render_template :edit 
    expecting <"edit"> but rendering with <""> 
# ./spec/controllers/dashboard_controller_spec.rb:37:in `block (3 levels) in <top (required)>' 
收到的錯誤

無論如何繞過這個錯誤,而無需刪除我的dashboard_controller中的load_and_authorize_resource?

+0

您是否在您的控制器中有編輯和索引方法?我在問,因爲您沒有在控制器代碼中指定這些方法。 –

+0

是的我有一個編輯方法,但它的簡單查找參數編輯方法,所以我沒有包括它 – coletrain

回答

0

當涉及Devise時測試控制器是一個惱人的棘手問題。你不提供你的login_user代碼,但我猜測它並沒有涵蓋所有的基礎。根據official Devise documentation,你需要幫助一些事情,包括監護人,Devise的效用方法等等。我會在這裏重複一遍,但是它會更長一些,你也可以去源碼。最相關的部分是:

如果您使用任何 devise的實用方法,控制器規格將無法使用。

作爲RSpec的護欄-2.0.0,並制定-1.1,把設計在 您的規格的最佳方法是簡單地添加以下到spec_helper ...

那麼他們的樣品中添加controller_macros.rb並調整一些其他的東西,你應該很好去。但是請注意,測試您的控制器規格與測試請求規格不同,您可能遇到這種解決方案無法解決的不同情況下的掛斷(請參閱我自己的一些痛苦和發現,在https://stackoverflow.com/a/13275366/9344)。