RSpec Setup in Rails 4
An up-to-date testing environment setup for Rails 4, including RSpec, Capybara, and FactoryGirl.
Gems
Gems gonna used are:
- rspec/rspec-rails: BDD Testing Framework for Rails.
- jnicklas/capybara: Acceptance Testing Framework.
- thoughtbot/factory_girl_rails: Fixtures.
- bmabey/database_cleaner: Database Cleaning.
Gems not covered:
- jfirebaugh/konacha: JavaScript Testing for Rails (Mocha + Chai).
- jonleighton/poltergeist: PhantomJS driver for Capybara (JavaScript).
- thoughtbot/capybara-webkit: Webkit driver for Capybara (Alternative to PhantomJS)
- thoughtbot/shoulda-matchers: Collection of testing matchers
Gemfile
Include the following:
Setup
- Initialize RSpec with
rails generate rspec:install
. - Create following directories
mkdir spec/factories spec/features spec/support
. - Create Database Cleaner configuration
spec/support/database_cleaner.rb
.
- Create Factory Girl configuration
spec/support/factory_girl.rb
.
- Require Capybara in
spec/rails_helper.rb
, afterrequire 'rspec/rails'
.
- Uncomment code in
spec/spec_helper.rb
. - Run
bundle binstubs rspec-core
to create a binstub for therspec
command so it can be run viabin/rspec
.
Commands
RSpec
rspec
: run all specs.rspec spec/models
: run all model specs.rspec spec/models/todo_spec.rb
: run specs in a file.
RSpec provides generator rails generate rspec:model widget
, which will create a new spec file in spec/models/widget_spec.rb
.
Available generators: scaffold
, model
, controller
, helper
, view
, mailer
, observer
, integration
.
RSpec _spec
file example:
Additions
Include Routes URL helpers
To use root_path
in specs, create spec/support/url_helpers.rb
.
Include I18n Shorthand
To use t
instead of I18n.t
in specs, create spec/support/i18n.rb
.
Include Helpers
Additional helpers can put in spec/support
subdirectories.