【问题标题】:RSpec test for redirect returns 200重定向的 RSpec 测试返回 200
【发布时间】:2011-09-12 23:44:52
【问题描述】:

我正在尝试测试这种重定向到同一页面但带有 www 的方法。前缀,如果它不存在。 它执行重定向,但 RSpec 测试返回“预期响应为 <:redirect>,但为 ”。这是为什么呢?

application_controller.rb

  def check_uri
    if request.subdomain.present? and request.subdomain.first != "www"
      redirect_to request.protocol + "www." + request.host_with_port + request.fullpath if !/^www/.match(request.host)
    end
  end

application_controller_spec.rb #

  describe :check_uri do
    it "should redirect to www" do
      { :get => "http://sub.lvh.me:3000/accounts/sign_up" }.
        should redirect_to "http://www.sub.lvh.me:3000/accounts/sign_up"
    end
  end

当我调试时,我得到: (

rdb:1) p response
#<ActionController::TestResponse:0x0000010277d988 @writer=#<Proc:0x0000010277c678@/Users/mm/.rvm/gems/ruby-1.9.2-p0@evergreen/gems/actionpack-3.0.7/lib/action_dispatch/http/response.rb:43 (lambda)>, @block=nil, @length=0, @header={}, @status=200, @body=[], @cookie=[], @sending_file=false, @blank=false, @cache_control={}, @etag=nil>

【问题讨论】:

  • 您是否调试过响应? response.body 的内容是什么?
  • 您在 application_controller 中有 check_uri 作为 before_filter 吗?
  • 是的,check_uri 是通过 before_filter 调用的。我在原始帖子中添加了调试响应。

标签: ruby-on-rails rspec


【解决方案1】:

您能测试一下响应的标头位置吗?

 response.header["Location"].should eq("http://www.sub.lvh.me:3000/accounts/sign_up"

)

【讨论】:

    【解决方案2】:

    您的测试没有达到您在 application_controller.rb 中定义的方法 check_uri,因为 RSpec 使用默认测试主机运行,例如端口 80 上的“test.host”。

    您应该调用应用程序控制器中存在的操作并将请求主机和端口存根,如下所示:

    describe :check_uri do
      it "should redirect to www" do
        @request.host = 'sub.lvh.me'
        @request.port = 3000
    
        get :index
    
        expect(response).to redirect_to "http://www.sub.lvh.me:3000/accounts/sign_up"
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 2015-04-08
      相关资源
      最近更新 更多