Testing Devise with RSpec (Rails 6+)

Today I learned how to test Devise with RSpec and Capybara. I used the Devise gem to authenticate my users, there are other alternatives like CanCan but I haven't tried yet. First of all, why bothering testing now all the things if : "Applications is running, all good, what's the matter?" BIG NO NO. As I mentioned in my previous post I began noticing more and more errors and was wondering how can I prevent this and that? Or how can I improve also this and that? Testing with RSpec has helped me understand test by test more how my application is working and of course learning a new "language" since, testing, believe it or not for me it was like learning a new language on top.

So, first things first. Installed the gems in my Gemfile:

gem 'devise', '4.7.1'

group :development, :test do
  gem 'factory_bot_rails'
  gem 'rspec-rails', '~> 4.0.0'
end

group :test do
  gem 'capybara', '3.32.2'
  ...
end

then I created my feature spec file named sign_in_spec.rb inside of my spec folder and inside of features folder too. Inside of my features I will attempt to create different tests depending on the user role ex. admin, user, visitor etc. For the moment will only focus on the basic user creation.

feature 'Sign in', :devise do
  let(:user) { create(:user) }
  scenario 'user cannot sign in if not registered' do
    signin('example@example.com', 'password')
    expect(page).to have_content 'E-Mail oder Passwort ungültig.'
  end

  scenario 'user can sign in with valid credentials' do
    signin(user.email, user.password)
    expect(page).to have_content 'Erfolgreich angemeldet'
  end

  scenario 'user cannot sign in with invalid email' do
    signin('invalid@mail.com', user.password)
    expect(page).to have_content 'E-Mail oder Passwort ungültig.'
  end

  scenario 'user canont sign in with invalid password' do
    signin(user.email, 'invalidpass')
    expect(page).to have_content 'E-Mail oder Passwort ungültig.'
  end
end

I created some scenarios and with the help of FactoryBot I created a user. let(:user) { create(:user) } and with the help of database cleaner I can create one user and then another one without crossing them.

With capybara I created a helper file inside of my support folder, which I called session_helper.rb

module Features
  module SessionHelpers
    def signin(email, password)
      visit new_user_session_path
      fill_in 'E-Mail', with: email
      fill_in 'Passwort', with: password
      click_button('Anmelden')
    end
  end
end

and then call it from my rails_helper.rb file:

...
RSpec.configure do |config|
  config.include Features::SessionHelpers, type: :feature

and also required devise.

This made my test go happy(green). I found this really helpfull and of course on my way I found a lot of great resources like this capybara cheat sheet.

No Comments Yet