Rails 5 Testing using Rspec
This basic tutorial will show you how to configure Rspec for Rails 5. This is really geared towards new Rails developers. My goal was to help give some guidance on what gem packages to install and how to create your first feature spec.
Create a new rails app.
Note: We're skipping the creation of tasks so that we can use Rspec instead of default MiniTask.
rails _5.0.0_ new my_rails_test --skip-test && cd my_rails_test
If you find yourself with errors and you don't have Rails 5 installed, I suggest reading this tutorial first.
Optional: This little in-line ruby script will remove all the comments in
Gemfile and make a
Gemfile.bak just in case.
ruby -pi.bak -pe "gsub(/^#.*\n/, '')" Gemfile
The next step is update our
Gemfile with the
# ### #Testing # ### gem 'spring-commands-rspec', :groups => [:development, :test] gem 'rspec-rails', :groups => [:development, :test] gem 'factory_girl_rails', :groups => [:development, :test] gem 'capybara', :groups => [:development]
Capybara is a tool aimed at helping you navigate through the page, fill out forms and other things that simulate user generated actions and behavior.
Now go to
Terminal and run bundle
rails g rspec:install
Let's also prepare ourselves for
bundle exec spring binstub --all
Organize your specs using directories. Let's first start by adding a features spec.
mkdir ./spec/features && cd ./spec/features
Create your first features spec.
Paste this into your first feature spec
spec/features/homepage_spec.rb. In feature spec, we use a new set of words including
scenario. This is the behavior driven development (BDD) style of wording.
require 'rails_helper' feature 'my home page' do scenario 'hello world message' do #Use capybara to auto complete forms and navigate visit('/') expect(page).to have_content("Hello World!") end end
Time to run the spec. In this case, all of them.
Congratulations! You've completed your first spec.
The next step is for you to solve the errors that Rspec is announcing.
Making the Most of Tasks
tasks are awesome. They can be used to create tiny little scripts that you'd otherwise have to memorize. For example, here are a few tasks I've created specifically to create, drop, and populate the test database. Yes, by now, I should be able to memorize them but the truth is, I can't and don't have to.
These suite of tasks are designed to drop, create, load and seed a test database. The only thing that's unique about them is
RAILS_ENV=test but this beats me having to memorize these little details.