zlog
zlog

Reputation: 3316

How do I test a redirect in sinatra using rspec?

I'm trying to test for a redirect on the homepage in my sinatra app (more specifically, a padrino app), in rspec. I've found redirect_to, however it seems to be in rspec-rails only. How do you test for it in sinatra?

So basically, I'd like something like this:

  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

Upvotes: 16

Views: 6450

Answers (4)

Artur INTECH
Artur INTECH

Reputation: 7396

March 2024 update:

it 'redirects to the root page' do
  get '/'
  expect(last_response).to be_redirect
  expect(URI(last_response.location).path).to eql '/locations'
end
  • Most of the time we are only interested in the correct path while the default host of example.org comes from Rack::Test and it should not be duplicated in the test.
  • follow_redirect! is not needed since we can take the new URL from the Location header.

Upvotes: 0

Uri Agassi
Uri Agassi

Reputation: 37419

In the new expect syntax it should be:

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

Upvotes: 0

Michael Kebbekus
Michael Kebbekus

Reputation: 171

More directly you can just use last_response.location.

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

Upvotes: 17

Ted Kulp
Ted Kulp

Reputation: 1433

Try this (not tested):

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

Upvotes: 22

Related Questions