when running a system test using capybarra, how can I test persistence layer?

27 Views Asked by At

I work on a rails app, where user can signup.

Once the user is signed up, I would like to check that the persisted user record matches some expectations, for example: the first name has been saved.

    it 'registers the user with the correct first_name' do

      visit new_user_registration_path

      within '#new_user' do
        fill_in 'user[first_name]', with: 'Foo'
        fill_in 'user[last_name]', with: 'Bar'
        fill_in 'user[email]', with: 'foo@bar'
        fill_in 'user[password]', with: 'password'
        click_button
      end
      user = User.find_by(email: 'foo@bar')
      expect(user.first_name).to eq('Foo')
    end
  end

In the example above, user is nil because the signup request didn't have time to complete yet. I have considered different options :

  1. only use expect(page) when dealing with system tests
  2. play with page.document.synchronize and wait for user to be available
  3. use 'workaround' using each example specificity (e.g: using User.last)

My understanding is that I should stick with option 1, but sometime user action have an effect that cannot is not rendered on the page.

What is according to you the best solution ?

1

There are 1 best solutions below

2
Les Nightingill On

the way I do it seems to be reliable, if your form is creating a User, you can do this:

expect{click_button}.to change{User.count}.by(1)
user = User.find_by(email: 'foo@bar')
expect(user.first_name).to eq('Foo')

if your form is editing a user you can do this:

user = User.find_by(email: '[email protected]')
expect{click_button}.to change{user.first_name}.to('Foo')