0

我正在尝试使用 rails-rpec 路由规范来测试基于不同用户代理的不同路由,但我找不到正确的方法或对象来存根。

我的方法如下所示:

require "spec_helper"

describe "articles routing" do
  describe "/articles/#slug" do

    it "routes to Articles#show" do
      get("/articles/fancy-slug").should route_to(controller: "articles",
                                                    action:     "show",
                                                    id:         "fancy-slug")
    end

    describe "when you have an iphone user agent" do
      before(:each) do
        # SOMETHING MAGICAL HAPPENS ALONG THE LINES OF THE LINE BELOW
        # request.user_agent = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25"
      end

      it "routes to Mobile::Articles#show" do
        expect(get: "/articles/fancy-slug").to route_to(controller: "mobile_articles",
                                                      action:     "show",
                                                      id:         "fancy-slug")
      end
    end

  end
end

但对于我的生活,我无法弄清楚如何存根请求、控制器或其他任何东西。大多数可用的文档似乎都引用了旧的/过时的get语法版本。

4

1 回答 1

0

我不确定这是否可行,但可以尝试以下方法:

如果您查看. _RouteToMatcher _ 但是该方法根据您作为参数传入的参数构建对象。因此,没有简单的方法可以从您的规范中访问请求对象。但是,为了构建这个虚拟请求,它调用controller#actionActionDispatch::Assertions::RoutingAssertions#assert_recognizesrequestroute_to

ActionController::TestRequest.new

所以你可以试试

ActionController::TestRequest.any_instance.stub(:user_agent).
  and_return "Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25"
于 2013-07-31T19:34:17.387 回答