2013-04-29 61 views
0

在我的系統中,我有一個擁有多個帳戶的公司的用戶。
用戶使用Devise登錄系統,並具有在CompaniesController中設置的名爲selected_company的虛擬屬性。
我想在這種情況下在AccountsController中進行多個測試。
我有這樣的代碼來sign_in用戶,此代碼工作得很好:如何使用步驟測試控制器以使用某些操作

before :each do 
    @user = create(:user) 
    @user.confirm! 
    sign_in @user 
end 

但我必須有,我試圖編寫的特定背景:

context 'when user already selected a company' do 
    before :each do 
    @company = create(:company) 
    @account = create(:account) 
    @company.accounts << @account 
    @user.selected_company = @company 
    end 

    it "GET #index must assings @accounts with selected_company.accounts" do 
    get :index 
    expect(assigns(accounts)).to match_array [@account] 
    end 
end 

但這種代碼不會工作中,當我運行它,我得到這個錯誤:

undefined method `accounts' for nil:NilClass 

我AccountsController#指數只有這樣的代碼:

def index 
    @accounts = current_user.selected_company.accounts 
end 

我是rspec和TDD的新成員,我有一些時間來測試我想要的一切,並且我想測試一切以實踐rspec。
我不知道這是測試這件事情的最好方法,所以我願意提供建議。

回答

0

最後,我發現了問題!
我改變了before聲明:

before :each do 
    @company = create(:company) 
    @account = create(:account) 
    @company.accounts << @account 
    controller.current_user.selected_company = @company 
end 

而且在改變assigns(accounts)assings(:accounts)(帶符號)預計方法。

0

替換:

expect(assigns(:accounts)).to match_array [@accounts] 

注意,:accounts而不是僅僅account
另外,正如我所看到的,您的規格中沒有@accounts。請也申明。 :)

+0

對不起,我輸入'@ accounts'而不是'@ account'。在我的代碼中,我使用了@account,它在before(:each)語句中聲明。 – squiter 2013-04-29 17:25:28

+1

是的,我推斷出這一點。但必須通知你,以防你實際上是'@ accounts'。 :) – kiddorails 2013-04-29 17:26:44

0

也許你沒有保存selected_company,當你在你的控制器上調用它時,它返回nil。

儘量節省@user.save集selected_company後:

context 'when user already selected a company' do 
    before :each do 
    @company = create(:company) 
    @account = create(:account) 
    @company.accounts << @account 
    @user.selected_company = @company 
    @user.save 
    end 

    it "GET #index must assings @accounts with selected_company.accounts" do 
    get :index 
    expect(assigns(accounts)).to match_array [@account] 
    end 
end 

希望能幫助你。

+0

嗨,我已經嘗試保存'@ user',但不是太工作...無論如何,謝謝你試圖幫助我:) – squiter 2013-04-29 20:35:17

+0

嘿布魯諾我已經意識到一個只有兩個地方它可以這個例外。 第一:我已經提到的地方。 第二:在這個'@ account.accounts << @ account'的代碼。 第二,嘗試使用create!(:company)創建公司工廠,可能是在調用它時。 – 2013-04-29 20:37:37

+0

'未定義的方法創建!爲#'我試着用FactoryGirl.create!並有相同的錯誤:( – squiter 2013-04-29 20:51:49

相關問題