Introduction to Rails Testing and Rspec

Source

3 environments

Every Rails app has 3 sides:

  • production
  • development
  • test

This distinction can be found on the config/database.yml file. This YAML configuration file has 3 different sections with 3 unique database setups.

development:
  adapter: sqlite3
  database: db/development.sqlite3
  pool: 5
  timeout: 5000

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: sqlite3
  database: db/test.sqlite3
  pool: 5
  timeout: 5000

production:
  adapter: sqlite3
  database: db/production.sqlite3
  pool: 5
  timeout: 5000

This allows you to setup and interact with test data without messing up with the data from the other environments.

rake db:test:prepare

If you want to destroy your testing database, you can rebuild it from scratch according to the specs defined in the development database.

Test:Unit testing framework default in Rails

A test folder is created when creating a new rails app. The test folder has:

  • fixtures: Are a way for organizing test data
  • functional: It holds tests for the controllers
  • integration: It holds tests involving any number of controllers interacting
  • unit: It holds tests for the models
  • test_helper.rb: Holds the default configuration of the tests

Fixtures

Fixture is sample data. It allows to populate the testing database with predefined data before running the tests.

They are database independent.

The assume the format is YAML

YAML-formatted fixtures are a human friendly way to describe the sample data

Preparing the app for testing

Before running tests, you need to make sure that the test database structure is current.

The following runs any pending migrations on the development environment and updates the schema.rb

$ rake db:migrate

The following recreates the test database from the current schema.rb

$ rake db:test:load

On subsequent attempts run the the following to check for pending migrations

$ rake db:test:prepare

Rake tasks for preparing the app for testing

Recreates the test database from the current environment’s schema

$ rake db:test:clone

Recreates the test database from the development structure

$ rake db:test:clone_structure

Recreate the test database from the current schema.rb

$ rake db:test:load

Check for pending migrations and load the test schema

$ rake db:test:prepare

Empty the test database

$ rake db:test:purge