簡體   English   中英

如何使用機架/測試來測試Sinatra重定向? 該應用程序有效,但測試不起作用

[英]How do I use Rack/Test to test Sinatra redirects? The App works, but the test doesn't

看來我丟失了一些非常基本的東西,或者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 ”插入重定向?

您的測試是錯誤的。

獲得重定向的狀態碼為302。因此正確的測試是:

期望(last_response.status)。到eq(302)

也許僅通過assert last_response.ok?來檢查此問題的更好方法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,因為您得到的是模擬而不是真實的響應。

正如@ sirl33tname指出的那樣,重定向仍然是重定向,因此我可以預期的最佳狀態是302,而不是200。如果我想測試重定向結束時是否得到了一個好的頁面,我應該測試ok? 不是狀態。

但是,如果我想測試最終使用的URL,則需要做一點點的事情,因為Rack / Test本質上是一個模擬系統(sic),並在重定向中返回頁面的模擬,而不是實際頁面。

事實證明,這很容易用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

這就是工作。

另一種方法是測試last_response.header['Location']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM