Migration Error When setting up rspec

2019-08-30 23:22发布

问题:

I'm trying to add rspec testing to an app I've already been working on. I've been following this tutorial: http://everydayrails.com/2012/03/19/testing-series-rspec-models-factory-girl.html which is from 2012, so I'm sure it was done using Rails 3. I installed rspec and capybara, ran bundle, and ran rails g rspec:install. I started writing the test of my Question model below, and when I ran it with rspec spec/models/question_spec.rb

I received the error: Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=test' to resolve this issue. I tried to run that and I received this error about one of my previous migrations:

==  ChangeTestTypeInScores: migrating =========================================
-- change_column(:scores, :test_type, "boolean USING CAST(test_type AS boolean)")
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: near "USING": syntax error: CREATE TABLE "scores" ("id" INTEGER     PRIMARY KEY AUTOINCREMENT NOT NULL, "test_type" boolean USING CAST(test_type AS boolean),     "name" varchar(255), "created_at" datetime, "updated_at" datetime, "user_id" integer, "month"     varchar(255), "year" varchar(255)) 

How can I correctly set up rspec without messing up my database, which works fine otherwise?

rails_helper.rb:

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'

require 'capybara/rspec'
ActiveRecord::Migration.check_pending!

.rspec:

--color
--require spec_helper
--require rails_helper
--format documentation

question_spec.rb:

require 'spec_helper'

describe Question do
  it "has a valid factory"
  it "is invalid without a body"
  it "is invalid without an answer"
end

I assume there's an issue with my changing the :test_type in my Scores model to boolean based on that error, but it all works great locally and on Heroku, so I don't want to mess with my database in order to run tests. Any help is appreciated.

UPDATE: I added this to the test.rb file:

config.active_record.maintain_test_schema = false

Also, I updated my version of rails to 4.1.6 after seeing many other related Stack Overflow issues. Now I get this error:

/Users/tambe257/.rvm/gems/ruby-2.0.0-p353/gems/activesupport-4.1.6/lib/active_support/dependencies.rb:241:in `load': cannot load such file -- /Users/tambe257/programming/rails_projects/fast_track/spec/models/question.rb (LoadError)

It looks like a problem with some dependencies, but I've been googling the error with no luck.

回答1:

On the update above I added this to the test.rb file, which actually cleared things up:

config.active_record.maintain_test_schema = false

I was then getting the (LoadError), but that was due to my file name not being completely correct. When you enter something like this below, be sure the route and file name are correct!

rspec spec/models/question_spec.rb