Skip to content

Instantly share code, notes, and snippets.

@livecodelife
Last active November 25, 2021 22:40
Show Gist options
  • Save livecodelife/fa5613e36493bfd71e8efd5ea9911c61 to your computer and use it in GitHub Desktop.
Save livecodelife/fa5613e36493bfd71e8efd5ea9911c61 to your computer and use it in GitHub Desktop.
Rails Engine Setup with RSpec, Capybara, FactoryGirl, and DatabaseCleaner

This sets up an easily testable mountable rails engine project

  1. rails plugin new <project_name> -T -d postgresql --dummy-path=spec/dummy --skip-turbolinks --skip-spring --mountable
  • -T skips the creation of the test directory and the use of Test::Unit
  • --dummy-path=spec/dummy sets up your dummy app in a spec directory
  • --skip-turbolinks & --skip-spring creates a project that does not use turbolinks or spring
  • --mountable creates a "mountable" and namespace-isolated engine.
  1. In project_name.gemspec file:
  • s.add_development_dependency 'rspec-rails' - user rspec in place of minitest (docs)
  • s.add_development_dependency 'capybara' - act as a user navigating your site in tests (docs)
  • s.add_development_dependency 'factory_girl_rails' - easily generate database objects without repetitive code in tests (docs)
  • s.add_development_dependency 'database_cleaner' - clean your database between tests (docs)
  1. Bundle and install (bundle exec or rails g) where required, create additional required files
  • bundle
  • rails g rspec:install
  • mkdir spec/support
  • touch spec/support/factory_girl.rb
  • touch spec/support/factories.rb
  • touch spec/support/database_cleaner.rb
  1. Add config data
  • In spec/rails_helper.rb require 'capybara/rails'

    • Uncomment Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
    • Change config.use_transactional_fixtures = true to ... = false
  • In spec/support/factory_girl.rb

    RSpec.configure do |config|
      config.include FactoryGirl::Syntax::Methods
    end
    
    
  • In spec/support/factories.rb

    FactoryGirl.define do
      <factories for each model go here>
    end
    
    
  • In spec/support/database_cleaner.rb

    RSpec.configure do |config|
    
      config.before(:suite) do
        DatabaseCleaner.clean_with(:truncation)
      end
    
      config.before(:each) do
        DatabaseCleaner.strategy = :transaction
      end
    
      config.before(:each, :js => true) do
        DatabaseCleaner.strategy = :truncation
      end
    
      config.before(:each) do
        DatabaseCleaner.start
      end
    
      config.after(:each) do
        DatabaseCleaner.clean
      end
      
      # Optional for formatting output of test suite runs (see comments)
      config.formatter = :documentation
    
    end
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment