Testing Best Practices

Guidelines and examples for writing effective tests in Rails using RSpec, FactoryBot, and Capybara.

Unit Tests

  • Focus on testing individual model methods and validations.
  • Use FactoryBot for creating test data.
# Example Unit Test
RSpec.describe User, type: :model do
  it { should validate_presence_of(:email) }
  it { should validate_uniqueness_of(:email) }

  describe '#full_name' do
    it 'returns the first and last name concatenated' do
      user = build(:user, first_name: 'John', last_name: 'Doe')
      expect(user.full_name).to eq('John Doe')
    end
  end
end

Integration Tests

  • Test interactions between models, controllers, and views.
  • Verify the expected flow of data and user actions.
# Example Integration Test
RSpec.describe 'User management', type: :request do
  describe 'POST /users' do
    it 'creates a new user' do
      expect {
        post users_path, params: { user: { email: 'test@example.com', password: 'password123' } }
      }.to change(User, :count).by(1)
    end
  end
end

System Tests

  • Use Capybara to simulate user interactions with the UI.
  • Test critical workflows end-to-end.
# Example System Test
RSpec.describe 'User login', type: :system do
  it 'allows a user to log in' do
    user = create(:user, email: 'test@example.com', password: 'password123')

    visit new_user_session_path
    fill_in 'Email', with: user.email
    fill_in 'Password', with: user.password
    click_button 'Log in'

    expect(page).to have_content('Signed in successfully.')
  end
end

Testing Tools

  • Use RSpec for expressive test cases.
  • Use FactoryBot for efficient test data generation.
  • Use Capybara for simulating user interactions.