1

非常に基本的なものが欠けているか、Rack/Test が Sinatra のリダイレクトに対応できていないようです。

おそらく、これを回避する方法があるか、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 」を挿入することを勝手に決めただけなのだろうか?

4

3 に答える 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 です。

于 2014-10-31T13:43:21.523 に答える
1

別の方法は、テストすることですlast_response.header['Location']

于 2018-12-27T14:42:13.087 に答える