Rspec を使用して単純なコントローラー仕様を作成する際に、非常にイライラする問題があります。問題を引き起こすメソッドが呼び出され#set_company
、現在サインインしているユーザーの親「アカウント」が設定されます。
def set_company
return false if !user_signed_in?
current_company = Company.find(current_user.company_id)
set_current_tenant(current_company)
end
私の仕様は次のようになります。
require 'spec_helper'
describe Api::V3::UsersController, :type => :controller do
describe 'GET #index' do
let(:user) { FactoryGirl.create(:user) }
let(:company) { user.company }
before {
allow(controller).to receive(:current_user) {user}
allow(controller).to receive(:current_tenant) {company}
}
it 'returns 200' do
get :index
expect(response.code.to_i).to eq 200
end
it 'assigns @users' do
get :index
expect(assigns(:users)).to eq [user]
end
end
end
問題は、2 番目のテストは緑ですが、最初のテストはそうではありません (その順序は正しいです!)。赤いのは、トリガーされたときにcompany
. これがその方法です:
user
が作成されています (company
依存関係です)。そのユーザーの ID は1であり、そのユーザーで作成された会社の ID も1です。- 2番目のテストがトリガーされ、すべてが素晴らしい
- 最初のテストがトリガー
Company
されますが、データベースに ID=1 のテストはありません。明らかに間違っている ID=2 の新しいテストがあり、set_company
メソッドが失敗します。
これは、database_cleaner を使用しているという事実に関連している可能性があると思いますが、それを処理する方法と、それについて何ができるかがまったくわかりません。手がかりをありがとうございました。