FactoryGirl build_stubbed & RSpec - Generates ID but fails to find id when testing Show action
Asked Answered
C

2

8

Here is my test. The error I am getting is ActiveRecord::RecordNotFound: Couldn't find MedicalStudentProfile with 'id'=1001. Am I using build_stubbed correctly?

RSpec Test

RSpec.describe MedicalStudentProfilesController, type: :controller do

 let!(:profile){build_stubbed(:medical_student_profile)}
 let!(:user){build_stubbed(:user)}

 describe 'GET show' do

  it 'should show the requested object' do
   sign_in user
   get :show, id: profile.id
   expect(assigns(:profile)).to eq profile
 end
 end

end

Controller

def show
 @profile = MedicalStudentProfile.find params[:id]
end
Cityscape answered 24/7, 2015 at 18:45 Comment(0)
L
9

build_stubbed doesn't save the record to the database, it just assigns a fake ActiveRecord id to the model and stubs out database interaction methods (like save ) such that the test raises an exception if they are called. Try using:

let!(:profile){create(:medical_student_profile)}

Lymn answered 24/7, 2015 at 19:10 Comment(4)
Thanks. I checked into build_stubbed to speed up controller tests, but it appears not to be applicable here.Cityscape
You can mock or stub the find method of the MedicalStudentProfile class to avoid the database hit. This way you are using mocks to specify the behavior of your controller instead of expecting a database result. I definitely recommend you the Rails 4 Test Prescriptions book if you want to learn more about this.Lymn
I get how mocking out the DB is good for test performance, but doesn't that kind of defeat whole the purpose of an integration test?Doubling
@Doubling I wouldn't consider a controller test as an integration test. The controller responsibility is to be a conduit between some part of the system where you adquire data and the views. However, the specific value that is passed is not part of the controller responsibility. So we can use mocks to specify that the controller calls the appropriate methods without effectively calling them. If I want to write an integration test I would write and end-to-end test using a tool like capybara. This way I will cover the entire system from the outside.Lymn
D
3

build_stubbed does not save the record to the database - it simply stubs a model to act like it has been persisted. This is great for model specs or other scenarios where you are not actually interacting with the database.

But for request and controller specs you need to use create so that your controllers can load the records from the database.

let!(:profile){ create(:medical_student_profile) }
let!(:user){ create(:user) }
Doubling answered 24/7, 2015 at 19:14 Comment(1)
Thanks! I wasn't sure if one could use them for controller specs.Cityscape

© 2022 - 2024 — McMap. All rights reserved.