我的两个测试中出现此错误:
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?
答案 0 :(得分: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 罗伯特