ruby-on-rails 如何在RSpec 3.12请求中测试redirect_back?

irlmq6kh  于 5个月前  发布在  Ruby
关注(0)|答案(1)|浏览(57)

我的应用程序将治疗作为一个任务列表进行管理。任务是通过从治疗显示视图调用的模式窗口创建和编辑的。当关闭任务表单时,I redirect_back到治疗,root_path作为回退位置:

def update    
    @task.updated_by = current_login    
    respond_to do |format|
      if @task.update_attributes(task_params)
        format.html { redirect_back fallback_location: root_path, notice: t('.Success') } 
        format.json { head :no_content }
      else
        format.html { redirect_back fallback_location: root_path, notice: "#{t('.Failure')}: #{@task.errors.full_messages.join(',')}" }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

字符串
使用Rspec测试总是会引发错误,因为它会重定向到root_path:

describe "update - PATCH /tasks/:id" do
    context "with valid parameters" do
      let(:new_attributes) do 
        {
          sort_code: "RSPEC-Updated"
        }
      end
      it "updates the requested task" do
        patch task_url(task), params: { 
          task: new_attributes 
        }.merge(extra_fields)
        expect(response).to redirect_to(treatment_url(task.parent))
      end
    end


如何配置测试以重定向到预期的位置并使其通过?

7vhp5slm

7vhp5slm1#

redirect_back方法使用request.referer重定向到上一个位置:

def redirect_back(fallback_location,, **args)
  if referer = request.headers["Referer"]
    redirect_to referer, **args
  else
    redirect_to fallback_location, **args
  end
end

字符串
因此,您需要将referer设置为所需的URL(就像在您的情况下,它应该设置为treatment_url(task.parent))。
你可以尝试在Rspec中设置referer,或者像上面提到的here on this answer

request.env['HTTP_REFERER'] = treatment_url(task.parent)

相关问题