我是Rails的新手,我正在尝试建立一个非常简单的模型。有三种模型类:Solution,Pro和Con。优点和缺点是这样的解决方案的孩子:
class Solution < ActiveRecord::Base
include BasicValidations
has_many :pros
has_many :cons
end
和
class Con < ActiveRecord::Base
belongs_to :solution
end
class Pro < ActiveRecord::Base
belongs_to :solution
end
但是,如果我尝试按如下方式运行测试:
def setup
@test_class = Solution
@solution = FactoryGirl.create(:solution)
end
test "Solutions can take pros" do
c = @solution.pros.create(description: "pros")
assert_includes(@solution.pros, c,"Could not add pro to solution")
end
我收到以下错误:
2) Error:
SolutionTest#test_Solutions_can_take_pros:
ActiveRecord::UnknownAttributeError: unknown attribute 'solution_id' for Pro.
test/models/solution_test.rb:12:in `block in <class:SolutionTest>'
...但只有部分时间,如果在rails控制台中手动执行相同的测试工作!
以下是数据库迁移:
class AddProsAndConsToSolution < ActiveRecord::Migration
def change
change_table :pros do |t|
t.belongs_to :solution, index: true
end
change_table :cons do |t|
t.belongs_to :solution, index: true
end
end
end
...和架构:
ActiveRecord::Schema.define(version: 20150323133049) do
create_table "cons", force: :cascade do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.string "description", limit: 255
t.integer "solution_id"
end
add_index "cons", ["solution_id"], name: "index_cons_on_solution_id"
create_table "pros", force: :cascade do |t|
t.string "description", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
t.integer "solution_id"
end
add_index "pros", ["solution_id"], name: "index_pros_on_solution_id"
create_table "solutions", force: :cascade do |t|
t.string "description", limit: 255
t.datetime "created_at"
t.datetime "updated_at"
end
end
我正在运行Rails 4.2.1。
有什么想法?看起来很简单,我一定错过了一些明显的东西,但它偶尔在测试和控制台中工作的事实让我感到困惑。
答案 0 :(得分:2)
尝试rake db:reset RAILS_ENV=test
,它将删除现有数据库(rake db:drop
),重新创建(rake db:create
),加载从当前开发数据库条件检索到的模式({{1} })和种子数据库(rake db:schema:load
),仅在您的rake db:seed
数据库配置中,在 config / database.yml 文件中确定,并通过设置{{1}来设置全局变量到test
。
如果在rails控制台中手动执行相同的测试
这很有效,因为测试是在测试 RAILS_ENV中运行的,而您的控制台是在开发 RAILS_ENV中。
您可以通过键入:RAILS_ENV
来访问测试环境的控制台。
答案 1 :(得分:0)
你完成了迁移测试数据库吗?
rake db:migrate RAILS_ENV=test