16

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
zlog
  • 3,316
  • 4
  • 42
  • 82

3 Answers3

22

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
Ted Kulp
  • 1,434
  • 13
  • 11
  • I'm getting the error: Failure/Error: follow_redirect! Sequel::DatabaseError: SQLite3::SQLException: no such table: locations . I'm guessing it is a database issue though. Will need to look into this further... – zlog Sep 16 '11 at 07:41
  • 1
    can you tell me where those `last_request`, `last_response` methods are documented... How are you able to call methods like `url` on those. I am new, so couldn't get it. – Arup Rakshit Mar 24 '14 at 22:54
  • @ArupRakshit See http://www.rubydoc.info/github/brynary/rack-test/master/Rack/Test/Methods for documentation of last_request/last_response. – Steve Midgley Dec 29 '14 at 20:09
  • @SteveMidgley Thanks for your reply.. Any help on this [problem](https://groups.google.com/forum/#!topic/rspec/WX-7KRK_EQY) ? – Arup Rakshit Dec 31 '14 at 06:24
  • Can also do something like `expect(last_response.location).to eq('http://example.org/locations')` without having to follow the redirect. – robert_murray Mar 04 '15 at 17:25
16

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
1

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
Uri Agassi
  • 36,848
  • 14
  • 76
  • 93