Blog

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.

  1. 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
  2. Open Mac Terminal and navigate inside your project directory (in my case rspec-and-capybara).
  3. Inside your project directory create:
    /server.rb
  4. 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
  5. In the project directory create the file below and notice that it doesn’t have a file extension:
    Rakefile
  6. Open Mac Terminal and navigate inside your project directory (in my case rspec-and-capybara).
  7. Inside Terminal, create a projects table following the do each command below.This will create projects and test tables. The test table will be used for testing the projects table for the actual website.
    rake db:migrate SINATRA_ENV=test
    rake db:migrate
  8. Still while in the project directory in Terminal, to do the RSpec and Capybara tests do:
    rspec specYou’ll notice that all tests will fail. This is normal behavior!
  9. 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
  10. 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
  11. To run your project, in Mac Terminal go to your project directory and do the command below:
    ruby server.rb
  12. 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
  13. Your files and directory structure should like something like below:

    sinatra ruby testing directory

Leave a Reply

To Top ↑