【问题标题】:How do I test a redirect in sinatra using rspec?如何使用 rspec 在 sinatra 中测试重定向?
【发布时间】:2011-11-17 11:24:27
【问题描述】:

我正在尝试在 rspec 中测试我的 sinatra 应用程序(更具体地说,一个 padrino 应用程序)的主页上的重定向。我找到了redirect_to,但它似乎只在 rspec-rails 中。您如何在 sinatra 中对其进行测试?

所以基本上,我想要这样的东西:

  it "Homepage should redirect to locations#index" do
    get "/"
    last_response.should be_redirect   # This works, but I want it to be more specific
    # last_response.should redirect_to('/locations') # Only works for rspec-rails
  end

【问题讨论】:

    标签: ruby rspec sinatra padrino


    【解决方案1】:

    试试这个(未测试):

    it "Homepage should redirect to locations#index" do
      get "/"
      last_response.should be_redirect   # This works, but I want it to be more specific
      follow_redirect!
      last_request.url.should == 'http://example.org/locations'
    end
    

    【讨论】:

    • 我收到错误:失败/错误:follow_redirect! Sequel::DatabaseError: SQLite3::SQLException: no such table: locations 。我猜这是一个数据库问题。需要进一步调查...
    • 你能告诉我那些last_requestlast_response 方法的记录在哪里吗...你怎么能在这些上调用像url 这样的方法。我是新人,所以无法获得它。
    • @ArupRakshit 有关 last_request/last_response 的文档,请参见 rubydoc.info/github/brynary/rack-test/master/Rack/Test/Methods
    • @SteveMidgley 感谢您的回复.. 对此problem 有任何帮助吗?
    • 也可以执行expect(last_response.location).to eq('http://example.org/locations') 之类的操作,而无需遵循重定向。
    【解决方案2】:

    您可以更直接地使用 last_response.location。

    it "Homepage should redirect to locations#index" do
      get "/"
      last_response.should be_redirect
      last_response.location.should include '/locations'
    end
    

    【讨论】:

      【解决方案3】:

      在新的expect 语法中应该是:

      it "Homepage should redirect to locations#index" do
        get "/"
        expect(last_response).to be_redirect   # This works, but I want it to be more specific
        follow_redirect!
        expect(last_request.url).to eql 'http://example.org/locations'
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 1970-01-01
        • 2012-06-28
        • 2012-02-12
        • 2013-02-07
        • 2012-02-19
        • 1970-01-01
        相关资源
        最近更新 更多