1

我的两个测试中有这个错误:

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错误?

我是否需要先创建一个对象,然后将其传递给 post create?

4

1 回答 1

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

是的,您是对的,您需要在运行此测试之前创建 Holder 实例。

但是你为什么要创建所有的 ivars,你需要新的吗?

如果不是,似乎代码可以干涸到

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 罗伯特

于 2012-07-11T16:32:47.890 回答