12
votes

I am on Rails 3.2 and I am using rspec (2.11.1). When I run my test suite with "rake spec" I get failures. When I run it with "rspec" everything passes. I've seen other mentions of this problem but nothing definitive that explains what is going on and what best practices are.

If I do "rake spec" or "rake tmp:clear && rake spec" my tests fail.

If I do "rspec" or "rspec spec" or "rake db:test:prepare && rspec" my tests pass.

I thought the only difference was that rake did "db:test:prepare" but if I do that manually before running rspec my tests pass so that can't be all of the story.

After doing a bit of reading I changed my Gemfile. Previously I had it set up as per "The RSpec Book" (p328) where it described putting the rspec gem inside a "group :development, :test" block. Having read some other SO posts I removed ":development" and did a bundle. Now "rake spec" does nothing. "rspec" still works as before.

Very confused...

3
done some further probing. with the Gemfile as per the rspec book (with :development, :test) running rspec uses the 'test' environment whereas rake spec uses the 'development' environment. Not sure right now why this is but will keep looking... - starfry
"RAILS_ENV='test' rake spec" works. I would have expected tests to default to the test environment without me having to be specific... - starfry
My answer was deleted (courtesy of @bhargav-rao) as a duplicated of stackoverflow.com/questions/15701298/… - Claudio Floreani

3 Answers

9
votes

Try running RAILS_ENV=test rake spec

3
votes

Here's what fixed it for me. I too was able to run rake spec RAILS_ENV=test I had my Gemfile like this

group :developmet do
    gem 'rspec-rails','2.9.0'
...
end
group :test do
    gem 'rspec-rails','2.9.0'
...
end

I changed it to this, making a block for test and development and putting it before the development state. I also made sure my db migrations had all made it into the test db. db:migrate RAILS_ENV=test

group :development,:test do
    gem 'rspec-rails','2.9.0'
        ...
end
group :development do
     ...
end
3
votes

According to rspec-rails github, put rspec-rails gem in the development and test groups of the Gemfile. This is because the test rake task loads development environment first before switching to test environment.

group :development, :test do
  gem 'rspec-rails'
end

Also, if you're using Gemfile, use "bundle exec rake spec" to run all your specs. To run single spec file, use "bundle exec rake rspec path/to/spec_file". Using "bundle exec" ensures you're using the correct rake command installed via your Gemfile instead of your system rake command.

Reference: https://github.com/rails/rails/issues/8591