RSpec请求.fullpath

时间:2011-06-03 08:21:20

标签: ruby-on-rails testing rspec

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

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方式。

1 个答案:

答案 0 :(得分:0)

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

@request.fullpath = "/my/path"

我的猜测是,当您在控制器规范中进行实际的获取/发布/放置/删除时,它将被覆盖。

你想直接设置完整路径而不是知道完整路径的任何原因都只是像“/ 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