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
錯誤?
我需要先創建一個對象,然後將其傳遞給創建後?
什麼是你創建的行動看起來像在控制器?某個地方你正在對尚未創建的東西調用'.id'。也許你做了''question.type = QuestionType.normal.id'這樣的事情 - 也就是說,你使用「種子」數據,而且它沒有加載?如果您發佈創建操作,它會幫助我們。 – MrDanA 2012-07-11 16:09:27
它是:'@holder = Holder.find_by_id(@ question.holder ***。id ***)'。稍後,您使用@ question.holder_id,它不引發異常。但是,您似乎希望避免創建沒有持有者的問題,例如通過驗證。 Rep to @MrDanA - 你應該把它作爲答案。 – emrass 2012-07-11 16:29:52