2016-04-05 45 views
0

我有以下表TodoList的:爲什麼create方法不會返回帶id的對象?

class TodoList < ActiveRecord::Base 
end 

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 

我創建的CRUD方法:

def create_todolist(params) 
     todolist = TodoList.create(list_name:params[:name], list_due_date: params[:due_date]) 
    end 

和我有followging測試:

 context "the code has to 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 

    end 

當我啓動測試給我下面的錯誤:

 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)>' 

這裏是我的項目目錄: enter image description here

看來,創建方法並不成功。請問有什麼問題?

+0

我認爲在'TodoList.find_by list_name:'mylist''中可能會有不必要的':'' –

+0

@pracede您能否顯示'TodoList'模型的代碼? –

+0

@MaximPontyushenko我添加了TodoList模型 – Pracede

回答

1

錯誤是從下面幾行代碼來:

assignment.create_todolist(:name=> 'mylist', :due_date=>due_date) 
    testList = TodoList.find_by list_name: 'mylist' 
    expect(testList.id).not_to be_nil 

在第一行,你想創建一個記錄。但是你實際上並沒有檢查模型是否成功保存。如果模型無法保存,您的find_by調用將返回nil。然後當你打電話給testList.id時,你基本上在一個零對象上調用id方法,導致你的錯誤。

您應該在測試中放置一個斷點並手動一行一行地檢查結果。有用的有效記錄方法是valid?,persisted?errors.full_messages。事情比這更容易調試。

您還應該練習閱讀錯誤,因爲您可以從中學到很多信息。例如:

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)>' 

所以在這裏你可以看到在assignment_spec.rb的第173行出現錯誤。 undefined method id for nil:NilClass告訴你,你試圖在一個零對象上調用id。知道find_by可以產生零對象,我覺得我找到了問題。我在這裏重複自己,但這只是我通過調試問題思考的一個例子。

相關問題