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

16

我正在尝试在我的Sinatra应用程序(更具体地说,是Padrino应用程序)中使用RSpec进行主页重定向测试。我发现了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
3个回答

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

我遇到了错误:Failure/Error: follow_redirect! Sequel::DatabaseError: SQLite3::SQLException: no such table: locations 。我猜测这是一个数据库问题。需要进一步调查... - zlog
1
你能告诉我那些 last_requestlast_response 方法在哪里有文档说明吗?你是如何在它们上面调用 url 方法的?我是新手,还不太明白。 - Arup Rakshit
@ArupRakshit 请参阅http://www.rubydoc.info/github/brynary/rack-test/master/Rack/Test/Methods 了解有关last_request/last_response文档的相关内容。 - Steve Midgley
@SteveMidgley 感谢您的回复。对于这个问题,有什么帮助吗? - Arup Rakshit
还可以这样做:expect(last_response.location).to eq('http://example.org/locations'),而无需遵循重定向。 - robert_murray

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接