Testing Sinatra Ruby Framework CRUD Operations with RSpec and Capybara Gems
Posted on August 10, 2015 in Ruby, Sinatra by Matt Jennings
This post describes CRUD (Create Read Update Delete) operations using the Sinatra Ruby framework, Active Record, and SQLite3 and testing with RSpec and Capybara Ruby gems.
Click on the links listed below to see code for separate files.
- If have done so, install the the RSpec, Capybara, Database Cleaner, and SQLite3 Ruby gems by doing:
gem install rspec
gem install capybara
gem install database_cleaner
gem install sqlite3
- Open Mac Terminal and navigate inside your project directory (in my case
rspec-and-capybara
). - Inside your project directory create:
/server.rb
- Also, inside the project directory create a spec directory for your RSepc and Capybara test files that have the following files listed below:
/spec/spec_helper.rb
/spec/features/list_projects_spec.rb
- In the project directory create the file below and notice that it doesn’t have a file extension:
Rakefile
- Open Mac Terminal and navigate inside your project directory (in my case
rspec-and-capybara
). - Inside Terminal, create a projects table following the do each command below.This will create
projects
andtest
tables. Thetest
table will be used for testing theprojects
table for the actual website.rake db:migrate SINATRA_ENV=test
rake db:migrate
- Still while in the project directory in Terminal, to do the RSpec and Capybara tests do:
You’ll notice that all tests will fail. This is normal behavior!rspec spec
- To pass all the tests create the Embedded Ruby (ERB) files below in a views directory. These files, and some of the HTML code in them, will match the GET, POST, PATCH, and DELETE requests inside server.rb.
/views/projects/index.erb
/views/projects/new.erb
/views/projects/show.erb
/views/projects/edit.erb
- To get CSS to display correctly, inside the project directory create a
public
directory and then create a CSS file like below:
/public/css/styles.css
- To run your project, in Mac Terminal go to your project directory and do the command below:
ruby server.rb
- To run the RSpec and Capybara tests, in Mac Terminal go to your project directory and do the command below. Hopefully you’ll pass 😉
rspec spec
- Your files and directory structure should like something like below: