Skip to content

Instantly share code, notes, and snippets.

@sebackend
Last active January 16, 2020 14:56
Show Gist options
  • Save sebackend/3b6aca0c7e4bd7ca806664bc1b637aca to your computer and use it in GitHub Desktop.
Save sebackend/3b6aca0c7e4bd7ca806664bc1b637aca to your computer and use it in GitHub Desktop.
Setup Rspec in Rails 5

1.- Setting up rspec

group :development, :test do
  gem 'rspec-rails', '~> 3.6.0'
end

1.- Instalar

$ bundle install
$ rails generate rspec:install

3.- Rspec con formato (opcional)

Agregar al archivo .rspec

--require spec_helper
--format documentation

4.- Binstub for the RSpec test runner

group :development do
  gem 'spring-commands-rspec'
end
$ bundle install
$ spring binstub rspec
$ rspec

5.- Deshabilitar Generadores

config/application.rb

config.generators do |g|
  g.test_framework :rspec,
  fixtures: false, 
  view_specs: false,
  helper_specs: false,
  routing_specs: false
end

I - Model specs

¿Qué testear?

  • When instantiated with valid attributes, a model should be valid.
  • Data that fail validations should not be valid.
  • Class and instance methods perform as expected.
  1. Crear spec para modelo de usuario
$ rails g rspec:model user

describe & context

  • describe : general functionality
  • context : specific state

* Factories

gem 'factory_girl_rails', '~> 4.8.0'
$ rails g factory_girl:model user

actualizar archivo config/application.rb

config.generators do |g|
  g.test_framework :rspec,
  view_specs: false,
  helper_specs: false,
  routing_specs: false
end

spec/factories/users.rb

FactoryGirl.define do
  factory :user do
    first_name "Sebastian"
    last_name "Meza"
    email "[email protected]"
    password "123456"
  end
end
user = FactoryGirl.build(:user) # use build for non-persisted data

*Database cleaner

Necesario para resetear la base de datos cada vez que se ejecute el comando rspec y así evitar errores por duplicidad de datos

gem 'database_cleaner', '~> 1.6.2'
$ bundle install

agregar configuración de database_cleaner spec/rails_helper.rb

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  config.before(:suite){ DatabaseCleaner.clean_with(:truncation) }
  config.before(:each) { DatabaseCleaner.strategy = :transaction }
  config.before(:each, :js => true) { DatabaseCleaner.strategy = :truncation }
  config.before(:each) { DatabaseCleaner.start }
  config.after(:each) { DatabaseCleaner.clean } 
end

II - Controller specs

$ rails g rspec:controller home

basic home_controller test

RSpec.describe HomeController, type: :controller do
  describe "#index" do
    it "responds successfully" do
      get :index
      expect(response).to_not be_success
    end
  end
end

Authenticated controllers

agregar lo siguiente en spec/rails_helper.rb

# helpers de Devise
include Warden::Test::Helpers
Warden.test_mode!

RSpec.configure do |config|
# Other stuff from the config block omitted ...

# Use Devise test helpers in controller specs
  config.include Devise::Test::ControllerHelpers, type: :controller
end

Test básico de prueba

require 'rails_helper'

RSpec.describe UsersController, type: :controller do

  describe "#index" do
    context "Unauthenticated user" do
      it "respond with redirection" do
        get :index
        expect(response).to have_http_status "302"
      end
    end

    context "Authenticated user" do
      before do
        @admin = FactoryGirl.create(:admin_user)
      end

      it "respond with 200" do
        sign_in(@admin)
        get :index
        expect(response).to have_http_status "200"
      end
    end
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment