Add required gems to Gemfile
group :development, :test do
gem 'rspec-rails', '~> 3.5'
gem 'shoulda-matchers'
gem 'factory_girl_rails'
gem 'database_cleaner', '~> 1.6.0'
end
# code coverage
gem 'simplecov', :require => false, :group => :testNow run bundle install to install newly added gems and generate rspec rails configuration with below command:
rails g rspec:install
it will generate 3 files for us
create .rspec
create spec
create spec/spec_helper.rb
create spec/rails_helper.rb
Open spec/rails_helper.rb and uncomment below line to load all the files inside support directories. We can
add all the configurations classes inside support directory and they will automatically loaded.
require 'simplecov'
SimpleCov.start 'rails'
.
.
.
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }Now that we are requiring all the files inside support directory, let's add support files to configure our requirements.
Lets start by creating spec/support directory
mkdir -p spec/support
Now create spec/support/database_cleaner.rb file and add below codes in it
# spec/support/database_cleaner.rb
RSpec.configure do |config|
config.before(:suite) { DatabaseCleaner.clean_with(:truncation) }
config.before(:each) { DatabaseCleaner.strategy = :transaction }
config.before(:each) { DatabaseCleaner.start }
config.append_after(:each) { DatabaseCleaner.clean }
endCreate spec/support/factory_girl.rb and add below codes. With below configuration, we can use factory girls's create method
directly without calling FactoryGirl e.g: create(:user, name: 'abc').
# spec/support/factory_girl.rb
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
endCreate spec/support/shoulda_matchers.rb and add below codes
#spec/support/shoulda_mathers.rb
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
endNow, you can add your specs and everything should work:
For example:
# app/model/user.rb
class User < ActiveRecord::Base
has_many :posts
validates :email, presence: true
end
# spec/models/user_spec.rb
RSpec.describe User do
it { should validate_presence_of :email }
it { should have_many :posts }
end