group :development, :test do
gem 'rspec-rails', '~> 3.6.0'
end
$ bundle install
$ rails generate rspec:install
Agregar al archivo .rspec
--require spec_helper
--format documentation
group :development do
gem 'spring-commands-rspec'
end
$ bundle install
$ spring binstub rspec
$ rspec
config/application.rb
config.generators do |g|
g.test_framework :rspec,
fixtures: false,
view_specs: false,
helper_specs: false,
routing_specs: false
end
¿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.
- Crear spec para modelo de usuario
$ rails g rspec:model user
- describe : general functionality
- context : specific state
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
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
$ 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
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
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