1
votes

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: '[email protected]', password: 'password')
    visit root_url
    fill_in 'Email', with: '[email protected]'
    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 '[email protected]'
    password 'password'
    password_confirmation 'password'
  end
end

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

1
Can you try expect(page).to have_content '[email protected]'Alex Avoiants
1 example, 0 failures as with an 'jdoe'Damir Nurgaliev
So the test with expect(page).to have_content 'jdoe' is also green, I understood correctly?Alex Avoiants
@OleksandrAvoyants yesDamir Nurgaliev

1 Answers

2
votes
# 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.