Skip to content

Instantly share code, notes, and snippets.

@troyleach
Last active June 27, 2021 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troyleach/ef940833e1a3415ddf89f79eb5863297 to your computer and use it in GitHub Desktop.
Save troyleach/ef940833e1a3415ddf89f79eb5863297 to your computer and use it in GitHub Desktop.
Implanmentaiton of rspec in a typical rails app

Implementation of rspec in rails

You will need to check the versions (last updated 8-8-18)

Pry

RSpec Rails

Factory Girl

faker

group :development, :test do
  gem 'pry'
  gem 'rspec-rails", '~> 3.7'
  gem 'faker', :git => 'https://github.com/stympy/faker.git', :branch => 'master'
end

capybara

database cleaner

launchy

selenium webdriver

shoulda matchers

group :test do
  gem 'factory_bot_rails'
  gem 'capybara'
  gem 'database_cleaner'
  gem 'launchy'
  gem 'selenium-webdriver'
  gem 'shoulda-matchers'

end
  • bundle install
  • rails g rspec:install

in .rspec add

--color
--require spec_helper
--format documentation

Create the factories directory

$ mkdir spec/factories

Configuration

  • in spec/rails_helper.rb
# require database cleaner at the top level
require 'database_cleaner'

# ... (this means existing code in the file)

# config.raise_errors_for_deprecations!
config.infer_spec_type_from_file_location!

# configure shoulda matchers to use rspec as the test framework and full matcher libraries for rails
Shoulda::Matchers.configure do |config|
  config.integrate do |with|
    # Choose a test framework:
    with.test_framework :rspec
    # Or, choose the following (which implies all of the above):
    with.library :rails
  end
end

# ...

RSpec.configuration do |config|
  # [...]
  # add `FactoryGirl` methods
  config.include FactoryGirl::Syntax::Methods

  # start by truncating all the tables but then use the faster transaction strategy the rest of the time.
  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
    DatabaseCleaner.strategy = :transaction
  end

  # start the transaction strategy as examples are run
  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
  # [...]
end
  • When using Capybara use see this and add the code

  • in config/application.rb add:

    config.generators do |g|
      g.test_framework :rspec,
                       fixtures: true,
                       view_specs: false,
                       helper_specs: true,
                       routing_specs: false,
                       controller_specs: true,
                       request_specs: false
      g.fixture_replacement :factory_girl, dir: "spec/factories"
    end

now in the command line run

$ rspec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment