如何使用Rack / Test测试Sinatra重定向?该应用程序工作,但测试没有

问题描述 投票:1回答:3

It would appear that either I am missing something very basic, or Rack/Test can't cope with Sinatra doing a redirect.

据推测,有一种解决方法或Rack / Test将无用。任何人都可以告诉我应该做些什么让它在这里工作?

(编辑:我最终想要实现的是测试我最终得到的页面,而不是状态。在测试中,last_response对象指向我的应用程序中不存在的页面,当然不是您实际访问的页面当你运行它时得到。)

一个示例应用:

require 'sinatra'
require 'haml'

get "/" do
  redirect to('/test')
end

get '/test' do
  haml :test
end

这可以像你期望的那样工作。转到'/'或'/ test'可以获得views / test.haml的内容。

但是这个测试不起作用:

require_relative '../app.rb'
require 'rspec'
require 'rack/test'

describe "test" do
  include Rack::Test::Methods

  def app
    Sinatra::Application
  end

  it "tests" do
    get '/'
    expect(last_response.status).to eq(200)
  end
end

这是运行测试时发生的情况:

1) test tests
   Failure/Error: expect(last_response.status).to eq(200)

     expected: 200
          got: 302

这就是last_response.inspect的样子:

#<Rack::MockResponse:0x000000035d0838 @original_headers={"Content-Type"=>"text/html;charset=utf-8", "Location"=>"http://example.org/test", "Content-Length"=>"0", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "X-Frame-Options"=>"SAMEORIGIN"}, @errors="", @body_string=nil, @status=302, @header={"Content-Type"=>"text/html;charset=utf-8", "Location"=>"http://example.org/test", "Content-Length"=>"0", "X-XSS-Protection"=>"1; mode=block", "X-Content-Type-Options"=>"nosniff", "X-Frame-Options"=>"SAMEORIGIN"}, @chunked=false, @writer=#<Proc:0x000000035cfeb0@/home/jonea/.rvm/gems/ruby-1.9.3-p547@sandbox/gems/rack-1.5.2/lib/rack/response.rb:27 (lambda)>, @block=nil, @length=0, @body=[]>

我想知道Rack / Test是否只是随意决定在重定向中插入'http://example.org'?

ruby sinatra rspec2 rack-test
3个回答
3
投票

你的测试是错误的。

获取重定向是状态代码302.所以正确的测试是:

expect(last_response.status).to eq(302)

也许更好的方法来检查这只是assert last_response.ok?

http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3

或者像github的例子:

get "/"
follow_redirect!

assert_equal "http://example.org/yourexpecedpath", last_request.url
assert last_response.ok?

是的,这总是example.org,因为你得到了一个模拟,而不是一个真正的回应。


2
投票

正如@ sirl33tname指出的那样,重定向仍然是一个重定向,所以我可以期待的最佳状态是302,而不是200.如果我想测试我是否在重定向结束时有一个好的页面,我应该测试ok?不地位。

但是,如果我想测试我最终会得到的URL,我需要做更多的事情,因为Rack / Test基本上是一个模拟系统(原文如此)并返回重定向页面的模拟,而不是实际页面。

但事实证明,这很容易用follow_redirect!覆盖。

测试成为:

it "tests" do
  get '/'
  follow_redirect!
  expect(last_response.status).to be_ok

  # ...and now I can test for the contents of test.haml, too...
  expect(last_response.body).to include('foo')
end

这就是工作。


0
投票

另一种方法是测试last_response.header['Location']

© www.soinside.com 2019 - 2024. All rights reserved.