我正在参加一门关于Rails with Active Record的Coursera课程,我正在完成我的第一个作业。作业的详细信息可以在这个链接和这个链接中找到。当我运行rspec时,我发现测试用例失败了,原来我的模式中没有ID列。课程中说,当我运行迁移时,ID列会像created_at和updated_at一样自动生成。有人知道为什么可能没有生成id列吗?我知道我可以通过在新的迁移中指定它来解决问题,但只是想知道原因。
以下是我当前拥有的架构:
这是todolist的迁移内容:
它生成的模型类:
以下是我当前拥有的架构:
ActiveRecord::Schema.define(version: 20161108162529) do
create_table "profiles", force: :cascade do |t|
t.string "gender"
t.integer "birth_year"
t.string "first_name"
t.string "last_name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "todo_items", force: :cascade do |t|
t.date "due_date"
t.string "title"
t.text "description"
t.boolean "completed", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "todo_lists", force: :cascade do |t|
t.string "list_name"
t.date "list_due_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "username"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end
这是todolist的迁移内容:
class CreateTodoLists < ActiveRecord::Migration
def change
create_table :todo_lists do |t|
t.string :list_name
t.date :list_due_date
t.timestamps null: false
end
end
end
它生成的模型类:
class TodoList < ActiveRecord::Base
end
按照要求在assignment.rb文件中插入记录的方法:
def create_todolist(params)
# accept a hash of todolist properties (`:name` and `:due_date`) as an input parameter. Note these are not 100% the same as Model class.
# use the TodoList Model class to create a new user in the DB
# return an instance of the class with primary key (`id`), and dates (`created_at` and `updated_at`) assigned
t1 = TodoList.new
t1.list_name = params["name"]
t1.list_due_date = params["due_date"]
t1.save
TodoList.first
end
无法通过的rspec代码:
context "rq03.2 assignment code has create_todolist method" do
it { is_expected.to respond_to(:create_todolist) }
it "should create_todolist with provided parameters" do
expect(TodoList.find_by list_name: "mylist").to be_nil
due_date=Date.today
assignment.create_todolist(:name=> 'mylist', :due_date=>due_date)
testList = TodoList.find_by list_name: 'mylist'
expect(testList.id).not_to be_nil
expect(testList.list_name).to eq "mylist"
expect(testList.list_due_date).to eq due_date
expect(testList.created_at).not_to be_nil
expect(testList.updated_at).not_to be_nil
end
当测试失败时,我收到的实际消息:
失败:
1) Assignment rq03 rq03.2 assignment code has create_todolist method should create_todolist with provided parameters
Failure/Error: expect(testList.id).not_to be_nil
NoMethodError:
undefined method `id' for nil:NilClass
# ./spec/assignment_spec.rb:173:in `block (4 levels) in <top (required)>'
# ./spec/assignment_spec.rb:14:in `block (2 levels) in <top (required)>'