Search code examples
rakehanami

Rake tests use a different database than Hanami?


I'm getting started with Hanami. (I use a different entity name, I started with reviews, not books, but otherwise I followed the instructions on the linked page.)

bundle exec hanami db prepare runs fine. The SQLite database is created. bundle exec hanami db runs fine

select * from reviews;

doesn't complain. bundle exec hanami server runs fine, I can load '/reviews', I can create a new one with '/reviews/new', then I can see the result again in the list. It definitely works with a database.

And then comes bundle exec rake test, which throws errors like

9) Error:
Add a review#test_0001_can create a new review:
Hanami::Model::Error: SQLite3::SQLException: no such table: reviews
    /home/ytg/.rvm/gems/ruby-2.5.1/gems/hanami-model-1.2.0/lib/hanami/repository.rb:362:in `rescue in create'
    /home/ytg/.rvm/gems/ruby-2.5.1/gems/hanami-model-1.2.0/lib/hanami/repository.rb:359:in `create'
    ...

I suspect that rake is working from a different database file than hanami, because the table should really be there. But why? And how can I make sure that they use the same database?

EDIT: adding the Rakefile just in case

require 'rake'
require 'hanami/rake_tasks'
require 'rake/testtask'
require 'rubocop/rake_task'

RuboCop::RakeTask.new

Rake::TestTask.new do |t|
  t.pattern = 'spec/**/*_spec.rb'
  t.libs << 'spec'
  t.warning = false
end

task default: :test
task spec: :test

Solution

  • You need to create the db for the test environment before you run them:

    HANAMI_ENV=test bundle exec hanami db prepare