Reputation: 1039
I can't figure out why stub can't create in this source.
I'm trying to test the logic inside if statement.
if user.nil? || company.nil?
is the condition. For that purpose, I made spec definition as below.
def introduce
accountant_request = AccountantRequest.with_introduce_request_status(:requested).find(params[:id])
company = Company.find_by(id: accountant_request.company_id)
user = User.find_by(id: company.try(:primary_user_id))
if user.nil? || company.nil?
redirect_to admin_accountant_requests_path, alert: 'There is no company or user' and return
end
Here's the spec. My expectation is Company.find_by(...) returns nil.
shared_examples 'post #introduce' do
subject(:response) { post 'introduce', params_for_introduce }
context 'error by user.nil? || company.nil?' do
it 'fail' do
allow_any_instance_of(Company).to receive(:find_by).and_return(nil)
expect(response).to have_http_status 302
expect(response).to redirect_to introduce_error_redirect_path2
end
end
Unfortunately, company = Company.find_by(id: accountant_request.company_id)
returns existing record not nil. So I could not examine inside if statement.
What's wrong? And what should I do in this case? Any idea is welcomed.
Upvotes: 0
Views: 780
Reputation: 1238
allow_any_instance_of
should be used for an instance of the Company class, but here find_by is called on the class itself
Try this (before executing the test subject i.e the request) :
allow(Company).to receive(:find_by) { nil }
Upvotes: 2