Separate Sinatra app's test database from development database?
Asked Answered
T

1

5

As a learning exercise, I am building a practice app using Sinatra, Datamapper and RSpec. I am using this template, which is basically a boilerplate for all the above.

The problem I am having is that the way RSpec and Datamapper seem to be configured, every time a spec is run that tests Database related functionality, those tests directly change my development database instead of a test database.

For example, I wish to create a few database objects before running the rest of the spec...

before(:all) {
  Region.new(:country => "Canada", :country_code => "CA").save
  ProductLine.new(:reference => "Molders").save
  Product.new(:name => "The Black Molder").save
  Cart.new(:price => 25.95).save
}

Yet every time I run RSpec, the above elements get added to my development database.

Why isn't a test database being generated instead? How can I get the test database to work properly?

This appears pretty similar to this issue here, except for Sinatra instead of Rails.

If it's any help, my code can be seen here.

Tan answered 21/2, 2012 at 10:59 Comment(0)
I
17

In spec_helper.rb file you are requiring my_app.rb file which in turn requires db.rb to set up your database, but this happens before you call set :environment, :test, so the configure :test block isn't being run (the environment is the default development at that stage).

Of course you can't call set environment :test before you require Sinatra, but you can set the RACK_ENV environment variable, which Sinatra checks when setting its environment.

So to make sure you're running in the test environment, add this to the top of spec_helper.rb (or somewhere else at the start of your tests, but before you require Sinatra):

ENV['RACK_ENV'] = 'test'

You could then remove the set :environment, :test line as it's now redundant.

This is similar to the other question you reference, but rack apps use RACK_ENV instead of RAILS_ENV.

Ine answered 21/2, 2012 at 14:6 Comment(1)
Thanks, I was putting ENV['RACK_ENV'] = 'test' in various places and getting frustrated as to why it wasn't picking it up - after reading your answer I put it at the top of spec_helper.rb before require 'sinatra' and now it works!Pestilential

© 2022 - 2024 — McMap. All rights reserved.