开发者

request.fullpath with RSpec

开发者 https://www.devze.com 2023-03-10 16:11 出处:网络
In my application controller, I have a couple of methods defined as follows: def store_location session[:return_to] = request.fullpath

In my application controller, I have a couple of methods defined as follows:

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

In order to test these methods, I need to find some way to set request.fullpath in RSpec. Does anybody know how I can accomplish this?

Update

When testing these methods, I'm using a shared example group, like so:

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

When including the shared example groups, I do something like the following:

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

include_examples "redirect back or default"

Thus, when a method use redirect_back_or_default, I just have to add the above code to its tests and I'm done.In this way, I can still be specific about testin开发者_开发百科g redirect_back_or_default without having to test against the implementation, which seems like a better way to do BDD to me.


You have access to a @request object that you might be able to set directly, like:

@request.fullpath = "/my/path"

My guess is that will be overridden when you make your actual get/post/put/delete, however, in the controller spec.

Any reason you want to set fullpath directly rather than knowing fullpath will just be something simple like "/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
0

精彩评论

暂无评论...
验证码 换一张
取 消