如何使用 rspec 在 sinatra 中测试重定向?

问题描述 投票:0回答:4

我正在尝试在 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
4个回答
22
投票

试试这个(未测试):

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

16
投票

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

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

1
投票

在新的

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

0
投票

大多数时候我们只对正确的路径感兴趣,而

example.org
的默认主机来自
Rack::Test
,并且在测试中不应该重复:

expect(URI(last_response.location).path).to eql '/locations'

附注将其作为答案而不是评论发布,以便引起注意,因为在我看来,它改进了上面的正确答案。

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