创建操作完成后的rspec控制器测试

时间:2013-08-19 13:06:51

标签: ruby-on-rails ruby-on-rails-3 rspec

我在使用rspec测试此代码时遇到问题 - 基于测试给出的错误,我知道测试是正确写入的 - 或多或少正确 - 因为它预期的数据是正确的,它只是没有得到它某些原因。我还应该注意,代码可以在浏览器中使用。

编辑道歉,如果不清楚的话。在此控制器(evaluations_controller)中,用户迭代给定组中的每个学生,并根据一组目标评估他们的进度。在新操作中,@student = groups.student.first - 当在创建操作中成功保存该学生的评估数据时,student_id增加1,新的student_id再次传递给新操作(因此下一个学生可以是评估) - 这循环直到没有更多的学生。

我要测试的是,在创建操作中保存评估后,student_id正在成功递增。

代码:

def create
...
  if @evaluation.save
    @id = params[:student_id]
    @id = @id.to_i + 1
    redirect_to evaluate_path({ student_group_id: @student_group, student_id: @id})   
  else  
    ... 
  end
end

Rspec测试:

it "should load the next student" do
  #set @id to current student.id +1
  @id = @student.id
  @id = @id.to_i + 1
  #post :create
  post :create, {student_group_id: @student_group, student_id: @student, evaluation: @attr}
  controller.params[:student_id].should eql @id                
end

错误:

Failure/Error: controller.params[:student_id].should eql @id expected: 2 got: "1"

1 个答案:

答案 0 :(得分:1)

您的代码似乎存在缺陷,因此您的测试不明确。

从收集代码开始,我知道你想要使用某种类型的下一个/以前的学生功能。看来你正在乱砍你的控制器测试来实现这一目标。

if @evaluation.save
    @id = params[:student_id]
    @id = @id.to_i + 1

您正在手动计算下一个ID。问自己:如果您正在使用student.id 1,并运行此计算,但student.id 2已被删除,会发生什么?

您收到ActiveRecord错误。

你需要更好的方法来拉动下一个学生。您应该为Student模型添加一个实例方法,以便为您处理:

  def next
    Student.where(id: id).order("id ASC").first
  end

在您的控制器中,您可以移动到下一位学生:

redirect_to evaluate_path({ student_group_id: @student_group, student_id: @student.next.id})

那么你的测试应该更加简单。