简体   繁体   中英

Testing Sinatra's redirect back in rspec

I am running a sinatra app and have a testing suite setup using rspec 2.7.0 and webrat 0.7.3 (both the most recent versions). I have an extensive set of tests for all of my request actions and it seems to be working fine. Today I discovered Sinatra's redirect back request-level helper and implemented it in a couple of areas of my application that were rendering forms with get requests which were taking parameters.

The nice thing about the redirect back helper is that if I have an action say:

get '/login' do
  @used_var = params[:var]
  haml :login
end

Which renders a form, I can have validation on the post request receiving the form:

post '/login' do
  # pretend User.authenticate pulls back a user entry from the database if there
  # is a valid username/password combination
  unless User.authenticate(params[:username], params[:password]).nil?
    redirect '/content'
  else
    flash[:notice] = "Invalid username/password combo"
    redirect back # will redirect back to the get '/login' request
  end
end

And if the form doesn't validate properly, it will redirect back to the page with the from and retain any parameters that were passed in without me having to worry about storing it to a session variable. The only problem is that rspec doesn't seem to want to play nicely with the redirect back helper. ie if I have a spec action that does this:

it 'should redirect to login when invalid username/password combo is received.' do
  get '/login', :var => 'value'
  fill_in 'username', :with => 'invalid_username'
  fill_in 'password', :with => 'invalid_password'
  click_button 'Submit'
  last_response.should be_redirect; follow_redirect!
  last_request.url.should include("/login")
end

The spec fails to pass because for some reason it seems that rspec or webrat isn't picking up on the redirect back helper and is instead redirecting the request back to the root url for my application ( '/' ).

What I want to know is whether there is a way to get rspec to redirect to the proper location in these instances? The actual application functions as expected when I test it with my browser (it redirects me to the first page with parameters), but the rspec tests don't pass properly.

尝试将:referer => '/login'传递给您的请求,以便redirect_back可以知道实际的'back'在哪里

Apparently this was a bug in rack , and it appears to have been fixed with the release of rack 1.3.0 . I tested this spec with rack 1.2.5 (most recent version prior to 1.3.0 release), and it failed, but upon upgrading to 1.3 , it started passing.

After some digging around, pretty sure that this pull request (here is the commit ) was the change that fixed it.

So it is no longer an issue in rack ~> 1.3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM