0

The test fails because of wrong email or password even though I create a new account and use it straight away

Heres the files

spec/factories/admins.rb

  FactoryGirl.define do
      factory :admin do
        email 'admin@example.com'
        password ('a'..'z').to_a.shuffle.join
      end
  end

spec/features/sign_in_spec.rb

require 'rails_helper'

describe 'Login', js: true do
  admin = FactoryGirl.create(:admin)
  it 'I can sign in' do
     visit '/admins/sign_in'
     fill_in 'Email', :with => admin.email
     fill_in 'Password', :with => admin.password
     click_button 'Log in'
     expect(page).to have_content('Signed in successfully')
  end
end
Tri Nguyen
  • 1,688
  • 3
  • 18
  • 46
  • Check what is getting stored inside `admin`. Also, could you share the controller action handling the login ? – bitsapien May 11 '17 at 03:03
  • Check out this comparable question: http://stackoverflow.com/questions/6154687/rails-integration-test-with-selenium-as-webdriver-cant-sign-in – jdgray May 11 '17 at 03:14

2 Answers2

0

Keep your admin = FactoryGirl.create(:admin) on before block then try.

before(:each) do
  @admin = FactoryGirl.create(:admin)
end

Now user this @admin to your test block.

Engr. Hasanuzzaman Sumon
  • 2,103
  • 3
  • 29
  • 38
0

The solution from Hasanuzzaman is correct, but you might benefit from an explanation why.

When your specs are read in, all it is doing is defining the tests. They aren't actually run immediately. By having your admin = FactoryGirl.create(:admin) line where it is it executes while defining the test and not at test run time. This means it has already been run before the database is cleared at the start of the tests so the record isn't actually there for the test. By moving it to a before block it is not actually run until the test is actually being run.

describe 'Login', js: true do
  before do
    @admin = FactoryGirl.create(:admin)
  end

  it 'I can sign in' do
     visit '/admins/sign_in'
     fill_in 'Email', :with => @admin.email
     fill_in 'Password', :with => @admin.password
     click_button 'Log in'
     expect(page).to have_content('Signed in successfully')
  end
end
Thomas Walpole
  • 48,548
  • 5
  • 64
  • 78