2014-02-20 75 views
0

現在,我的組織控制器列出當前用戶擁有成員身份的所有組織。我知道我的測試是錯誤的,但我無法弄清楚它是如何正確的。如何爲嵌套控制器索引編寫測試

organizations_controller.rb

def index 
    @user = current_user 
    @organizations = @user.organizations.all 
end 

這是工作的罰款,該模型是確定和意見顯示正確的組織。

我想爲它寫一個測試,但不知何故我卡住了。這裏是我廠:

factory :organization do 
    name "example" 
    website "www.aquarterit.com" 
    after(:create) {|organization| organization.users = [create(:admin)]} 
    end 

這裏是我的測試:

describe "GET #index" do 
    it "populates an array of organizations where the user has membership" do 
     organization = create(:organization) 
     get :index 
     expect(assigns(:organizations)).to eq([organization]) 
    end 
    it "renders the :index view" do 
     get :index 
     expect(response).to render_template ("index") 
    end 
end 

結果自然是:

expected: [#<Organization id: 1, name: "example", website: "www.aquarterit.com", created_at: "2014-02-20 22:10:17", updated_at: "2014-02-20 22:10:17">] 
      got: nil 

     (compared using ==) 

回答

0

那是因爲你在測試中創造organization不與user相關聯通過致電current_user返回。存根current_user方法來回報您的用戶

describe "GET #index" do 
    it "should populate an array of organizations where the user has membership" do 
     organization = create(:organization) 
     controller.stub(:current_user).and_return(organization.user) 
     get :index 
     expect(assigns(:organizations)).to eq([organization]) 
    end 

    it "renders the :index view" do 
     get :index 
     expect(response).to render_template ("index") 
    end 
end 
+0

恐怕不行......我得到:'1)OrganizationsController GET #INDEX應該填充組織的陣列,其中用戶作爲成員 故障/錯誤:controller.stub(:current_user).and_return(organization.user) NoMethodError: 未定義的方法'用戶'爲#

+0

不確定是否相關,但我正在使用設計 –

相關問題