Skip to content
This repository has been archived by the owner on Mar 27, 2023. It is now read-only.

Setting up the tests

Aly Badawy edited this page Mar 4, 2023 · 5 revisions

In this application, we use Jest as the engine for React testing (with React testing library), as well as using RSpec and Capybara to test the rails application.

We also use FactoryBot for fixtures and building instances of models through the test, and clean the database between tests using database-cleaner gem.

Jest and React Testing Library:

  • To add Jest testing libraries, add the following to your package.json file:
    "dependencies": {
      "react-dom": "^18.2.0"
    },
    "devDependencies": {
      "@babel/preset-env": "^7.17.10",
      "@babel/preset-react": "^7.16.7",
      "@testing-library/react": "^13.2.0",
      "babel-jest": "^28.1.0",
      "jest": "^28.1.0",
      "react-test-renderer": "^18.1.0",
      "jest-environment-jsdom": "^29.4.3",
      "@testing-library/jest-dom": "^5.16.1",
      "ts-jest": "^29.0.5",
      "@types/jest": "^29.4.0",
    },
    "scripts": {
      "test": "jest --silent --noStackTrace --coverage"
    }
    
  • Create a file named app\javascript\jest\jest.setup.ts with the following content:
import '@testing-library/jest-dom';
  • Configure Jest by creating a file named jest.config.js with the contents of: jest.config.js
  • Run yarn install -create a file named app\javascript\jest\pass.test.tsx with the following content:
import React from 'react';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';

describe('Test', () => {
  it('passes!', () => {
    render(<div>This should pass</div>);
    const paragraph = screen.getByText('This should pass');
    expect(paragraph).toBeInTheDocument();
  });
});
  • Run yarn test

RSpec, Capybara and FactoryBot:

  • Update your ./Gemfile to include the following:

    group :development, :test do
      gem 'capybara'
      gem 'database_cleaner'
      gem "debug", platforms: %i[ mri mingw x64_mingw ]
      gem 'dotenv-rails'
      gem 'factory_bot_rails'
      gem 'faker'
      gem 'pry-byebug'
      gem 'pry-rails'
      gem 'rspec-rails'
      gem 'shoulda-matchers'
    end
    
  • Run the following commandS:

    bundle install
    rails generate rspec:install
    
  • Edit spec/rails_helper.rb to become as: rails_helper.rb

  • Edit spec/spec_helper.rb to become as: spec_helper.rb

  • Create ./spec/support/factory_bot.rb with the content of: factory_bot.rb

Create a file named spec\system\pass_spec.rb with the following content:

# frozen_string_literal: true

require "rails_helper"

RSpec.describe "Test" do
  it "Passes" do
    expect(1 + 1).to eq(2)
  end
end

then run bundle exec rspec