2013-04-29 63 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

相关问题