Damir Nurgaliev Damir Nurgaliev - 1 month ago 20
Ruby Question

Testing Devise Using capybara rspec and factory girl

i'm new at rails and i'm testing my devise gem User with capybara rspec and factory girl.

Here's spec code:

require 'rails_helper'
RSpec.describe User, type: :request do
it "displays the user's email after successful login" do
user = FactoryGirl.create(:user, email: 'test@test.com', password: 'password')
visit root_url
fill_in 'Email', with: 'test@test.com'
fill_in 'Password', with: 'password'
click_button 'Log in'
expect page.has_content?('jdoe')
end
end


The problem is in


expect page.has_content?('jdoe')
No matter what i put instead 'jdoe' test works perfectly without any errors.


Here's factory:

FactoryGirl.define do
factory :user do
email 'test@test.com'
password 'password'
password_confirmation 'password'
end
end


Maybe I missed something or going with a wrong way. How should I test here?

max max
Answer
# spec/features/sessions_spec.rb
require 'rails_helper'
RSpec.feature "Sessions" do
  scenario "displays the user's email after successful login" do
    user = FactoryGirl.create(:user)
    visit root_url
    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Log in'
    expect(page).to have_content("Signed in successfully")
    # will give a false postitive if form is rerended?
    expect(page).to have_content(user.email) 
  end
end

A few things here:

  1. Use a feature and not a request spec for end to end testing.
  2. Don't hardcode object attributes. The whole point of factories is that the factory takes care of generating unique data so that the tests don't give false positives due to residual state.
  3. Use expect(page).to instead of expect page.should. expect(page).to sets a subject and uses a RSpec matcher which will show you the text of the page in an error message if it does not match.