【问题标题】:request.fullpath with RSpec带有 RSpec 的 request.fullpath
【发布时间】:2011-06-09 03:51:22
【问题描述】:

在我的应用程序控制器中,我有几个方法定义如下:

def store_location
  session[:return_to] = request.fullpath
end

def redirect_back_or_default(default)

  # make sure this method doesn't redirect back to the current page
  if session[:return_to] == request.fullpath
    redirect_to default
  else
    redirect_to(session[:return_to] || default)
  end

  session[:return_to] = nil
end

为了测试这些方法,我需要想办法在 RSpec 中设置request.fullpath。有谁知道我如何做到这一点?

更新

在测试这些方法时,我使用的是共享示例组,如下所示:

shared_examples_for "redirect back or default" do
  it "should redirect" do
    request
    response.should be_redirect
  end

  describe "when the user has a back page" do
    it "should redirect to back"
  end

  describe "when the user does not have a back page" do
    it "should redirect to default" do
      request
      response.should redirect_to(default_path)
    end
  end
end

当包含共享示例组时,我会执行以下操作:

before(:each) do
  def request
    post :create, :user => @attr
  end
  def default_path
    :root
  end
end

include_examples "redirect back or default"

因此,当一个方法使用redirect_back_or_default时,我只需将上面的代码添加到它的测试中就可以了。这样,我仍然可以具体测试redirect_back_or_default,而无需针对实现进行测试,这对我来说似乎是一种更好的 BDD 方式。

【问题讨论】:

    标签: ruby-on-rails testing rspec


    【解决方案1】:

    您可以访问可以直接设置的@request 对象,例如:

    @request.fullpath = "/my/path"
    

    我的猜测是,当您在控制器规范中进行实际的 get/post/put/delete 时,它​​将被覆盖。

    您想直接设置完整路径而不是知道完整路径的任何原因都只是像“/mock”这样简单的东西吗?

    class MocksController < ApplicationController
      def show
      end
    end
    
    describe MocksController do
      before do
        MyApp::Application.routes.draw do
          resource :mock, :only => [:show]
        end
      end
    
      after do
        Rails.application.reload_routes!
      end
    
      it "something" do
        get :show
        should # something
      end
    end
    

    【讨论】:

    • 很抱歉,但我不完全理解您在测试顶部使用 routes draw 命令在做什么。你能解释一下吗?
    • 路由的东西是必要的,只是为了获得 ApplicationController 的子类。
    • 对不起,我认为我的问题并没有完全清楚。我马上更新。
    • 哦,你不需要绘制路线,rspec2 有一些更好的东西:relishapp.com/rspec/rspec-rails/v/2-6/dir/controller-specs/…
    猜你喜欢
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多