rspec create()方法不起作用

时间:2017-03-31 11:04:57

标签: ruby-on-rails ruby rspec factory-bot

我正在开发像bento这样的在线学习门户网站。对于用户解锁下一课程,他们必须在分配任何先前课程时完成至少一次来自其他用户的提交(由当前用户完成)。考虑到这个逻辑,我有一个rspec测试,我测试过该页面是否被重定向到其他用户的提交?为了通过测试,我必须创建虚拟提交。为此,我使用的是create()方法,但重定向到提交页面的测试失败,但它在网站上运行正常。在submission_controller中负责重定向的代码是

def review_submission
 @submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i)
                        .shuffle[1]
 if @submission.nil?
  redirect_to @assignment
 else
  redirect_to assignment_submission_path(assignment_id: @assignment.id, id: @submission.id)
 end
end

测试代码是

it "redirects to submission path" do
    admin_user = create(:admin_user)
    sign_in admin_user
    user = create(:user)
    sign_in user
    assignment = create(:assignment, admin_user_id: admin_user.id)
    #I was creating dummy submissions data using rspec create method.
    submission = create(:submission, lesson_id: 1) 
    post :create, params: { submission: attributes_for(:submission, user_id: user.id), assignment_id: assignment.id}

    expect(response).to redirect_to assignment_submission_path( assignment_id: assignment.id, id: Submission.last.id)
  end

虚拟数据来自FactoryGirl

factory :submission do
  user_id 1
  assignment_id 1
  lesson_id 2
  content "this is the submission of my assignment"
  factory :invalid_submission do
    content ""
  end
end

任何建议都非常感谢。提前谢谢。

1 个答案:

答案 0 :(得分:1)

看起来@submission为零,因此它会将您重定向到Attachments#show页面,而不是Submissions#show page。您可以将其设置为:

@submission = Submission.where('lesson_id < ?', current_user.submissions.last.assignment.lesson_id.to_i).shuffle[1]

它试图根据current_user.submissions找到提交内容。您的工厂只是提交提交:

submission = create(:submission, lesson_id: 1) 

默认user_id1,这可能不是您已登录用户的ID(因为您在其上方创建了管理员用户)。尝试将user_id传递给FactoryGirl创建的提交内容。也可能也想传递assignment_id,因此提交将正确属于作业。

submission = create(:submission, lesson_id: 1, user_id: user.id, assignment_id: assignment.id) 

然后应该将提交内容分配给您的用户,并希望控制器能够找到它并且您的测试将通过。