2012-07-11 59 views
1

我有這樣的錯誤在我的兩個測試:名爲id的零,這將誤在控制器測試4

test "should create question" do 
    assert_difference('Question.count') do 
    post :create, question: { question: 'apple', answer: "good", holder_id: 2} 
    end 
end 

test "should not create question" do 
    invalid_answer = "a" * 145 
    assert_difference('Question.count',0) do 
    post :create, question: { answer: invalid_answer } 
    end 
    assert_template 'new' 
end 

我創建行動

#create action 
def create 
    @question = Question.new(params[:question]) 
    @holder = Holder.find_by_id(@question.holder.id) 
    if @question.save 
    flash[:success] = "Question Saved" 
     redirect_to holder_path(@question.holder_id) 
    else 
     render 'new' 
    end 
end 

堆棧跟蹤顯示它是創造兩條線。但是,我怎麼得到Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id錯誤?

我需要先創建一個對象,然後將其傳遞給創建後?

+1

什麼是你創建的行動看起來像在控制器?某個地方你正在對尚未創建的東西調用'.id'。也許你做了''question.type = QuestionType.normal.id'這樣的事情 - 也就是說,你使用「種子」數據,而且它沒有加載?如果您發佈創建操作,它會幫助我們。 – MrDanA 2012-07-11 16:09:27

+1

它是:'@holder = Holder.find_by_id(@ question.holder ***。id ***)'。稍後,您使用@ question.holder_id,它不引發異常。但是,您似乎希望避免創建沒有持有者的問題,例如通過驗證。 Rep to @MrDanA - 你應該把它作爲答案。 – emrass 2012-07-11 16:29:52

回答

1
@question = Question.new(params[:question]) 
    @holder = Holder.find_by_id(@question.holder.id) 

是的你是對的,你需要在運行這個測試之前創建Holder實例。

但是你爲什麼要創建所有的ivars,你需要新的嗎?

如果沒有它似乎可以把代碼dryed高達

def create 
    question = Question.new(params[:question]) 
    if question.save 
    flash[:success] = "Question Saved" 
     redirect_to holder_path(question.holder) # but some checks are in order here, no? 
    else 
     render 'new' 
    end 
end 

HTH 羅伯特

相關問題