Search code examples
ruby-on-railstestingrspeccapybararspec-rails

Query after POST returns Nil unless following expect(page)


After I submit a POST, I check the DB to see if it is stored.

feature 'foo' do
  scenario 'bar', :js => true do
    navigate_to_form
    within '.form-class' do
      fill_form
      click_on 'Save'
    end
    ...

If I perform a check right after my submission, it returns Nil on the query.

expect(ModelName.last.attribute).to eq("attribute_value")
  => undefined method 'attribute' for nil:NilClass

If I perform it after a page(expect) it returns the appropriate object.

expect(page).to have_text('text_on_page')
expect(ModelName.last.attribute).to eq("attribute_value")
  =>true

Solution

  • The server is running in a separate thread. Since click on 'Save' doesn't wait for a response, when you immediately check the database, the server hasn't had a chance to do its work. When you wait for text to appear, you know the server update has completed.