DEV Community

Thato Semoko
Thato Semoko

Posted on

RSpec + Capybara: Submitting forms

In the past I thought testing my code was a waste of time until the day my web application did not perform well in production -it was embarrassingly buggy.

Since then I discovered RSpec and I fell in love with the tool and also behaviour driven development.RSpec rails becomes even more powerful with Capybara gem for even more robust testing with a look into how the user will interact with users.

For instance, testing how the user signs up, i.e, filling in the sign up form.

require 'rails_helper'

RSpec.describe "User Registration", type: :system do
  before do
    driven_by(:rack_test)
  end

  context "signs up a new user" do
    it "signs a user up" do
      visit '/users/sign_up'
      within("#new_user") do
        fill_in 'Email', with: 'user@example.com'
        fill_in 'Password', with: 'password'
      end
      click_button('Sign up') # submits the form
      expect(page).to have_content 'You have signed up successfully'
    end
  end
end

We can take things more deeper to test what parameters users submit to the database through your forms. Let's start with a User model that requires full_name to be present on new sign ups.

class User < ApplicationRecord
  ...  
  validates :full_name, presence: true
  ...
end

Then we want to make sure that the form is not submitted unless this parameter is missing.

require 'rails_helper'

RSpec.describe "User Registration", type: :system do
  before do
    driven_by(:rack_test)
  end

  context "does not sign up a new user" do
    it "signs a user up" do
      visit '/users/sign_up'
      within("#new_user") do
        fill_in 'Email', with: 'user@example.com'
        fill_in 'Password', with: 'password'
      end
      click_button('Sign up') # submits the form
      expect(page).to have_content 'First name can\'t be blank'
    end
  end
  context "signs up a new user" do
    it "signs a user up" do
      visit '/users/sign_up'
      within("#new_user") do
        fill_in 'Full name', with: 'User Example'
        fill_in 'Email', with: 'user@example.com'
        fill_in 'Password', with: 'password'
      end
      click_button('Sign up') # submits the form
      expect(page).to have_content 'You have signed up successfully'
    end
  end
end

The combination of these technologies has made me fall in love with testing (BDD). What are some of the use cases you have implemented with RSpec and Capybara.

Top comments (0)