Damir Nurgaliev Damir Nurgaliev - 1 month ago 17
Ruby Question

Capybara rails testing error

I'm new at rails. I'm using a copybara gem for testing the devise. Here is a test code

require 'test_helper'

class UserTasksTest < ActionDispatch::IntegrationTest
test 'Should create a new user' do
visit root_url
click_link 'Sign up'
fill_in "Email", with: 'capybaratest@test.ru'
fill_in "Password", with: 'capybara'
fill_in "Password confirmation", with: 'capybara'
click_button 'Sign up'
within("h1") do
assert has_content?(user.email)
end
end
end


After running a test i've got an error:


undefined local variable or method `user'


How should I write the test correctly?

Answer

You are testing the creation of a new user and expecting its email to be displayed after the sign up. So, the user variable is not defined and for that reason you are getting this error. Try the following:

require 'test_helper'

class UserTasksTest < ActionDispatch::IntegrationTest
  test 'Should create a new user' do
    visit root_url
    click_link 'Sign up'
    fill_in "Email", with: 'capybaratest@test.ru'
    fill_in "Password", with: 'capybara'
    fill_in "Password confirmation", with: 'capybara'
    click_button 'Sign up'
    within("h1") do
      assert has_content?('capybaratest@test.ru')
    end
  end
end

Just to clarify, one situation that you would use the user variable is i.e the login flow: before you start the test you would create a valid user and set the user variable with this new user... in this way you would be able to fill in email/password fields with email and password used to create the user, and finally check if it displays i.e "Welcome #{user.name}".