0

私のシステムでは、複数のアカウントを持つ 1 つの会社を持つユーザーがいます。
ユーザーは Devise を使用してシステムにサインインし、CompanysController で設定された selected_company という仮想属性を持っています。
このシナリオでは、AccountsController で複数のテストを行いたいと考えています。
ユーザーをサインインするためのこのコードがあります。このコードはうまく機能します。

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#index には次のコードしかありません:

def index
  @accounts = current_user.selected_company.accounts
end

私は rspec と TDD の初心者で、必要なものすべてをテストする時間があり、rspec を実践するためにすべてをテストしたいと考えています。
これがこのことをテストする最良の方法であるかどうかはわかりませんので、提案をお待ちしています。

4

3 に答える 3

0

おそらくselected_companyを保存していないので、コントローラーでこれを呼び出すとnilが返されます。

@user.saveselected_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

お役に立てれば幸いです。

于 2013-04-29T20:30:09.767 に答える
0

と置換する:

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

:accountsの代わりに注意してくださいaccount。また、私が見ているように、仕様に
はありません。@accountsそれも宣言してください。:)

于 2013-04-29T17:21:47.623 に答える
0

最後に、私は問題を見つけました!ステートメントを次
のように変更しました。before

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

そして、expect メソッドで (with symbol) に変更assigns(accounts)しました。assings(:accounts)

于 2013-04-29T21:14:26.200 に答える