2016-08-06 12:54:50 -04:00
|
|
|
require "abstract_unit"
|
|
|
|
require "active_support/core_ext/integer/time"
|
|
|
|
require "active_support/core_ext/numeric/time"
|
2015-04-15 14:30:27 -04:00
|
|
|
|
|
|
|
class ConditionalGetApiController < ActionController::API
|
2015-04-21 16:15:45 -04:00
|
|
|
before_action :handle_last_modified_and_etags, only: :two
|
2015-04-15 14:30:27 -04:00
|
|
|
|
|
|
|
def one
|
2015-04-21 16:15:45 -04:00
|
|
|
if stale?(last_modified: Time.now.utc.beginning_of_day, etag: [:foo, 123])
|
2015-07-17 21:48:00 -04:00
|
|
|
render plain: "Hi!"
|
2015-04-15 14:30:27 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def two
|
2015-07-17 21:48:00 -04:00
|
|
|
render plain: "Hi!"
|
2015-04-15 14:30:27 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-08-06 13:55:02 -04:00
|
|
|
def handle_last_modified_and_etags
|
|
|
|
fresh_when(last_modified: Time.now.utc.beginning_of_day, etag: [ :foo, 123 ])
|
|
|
|
end
|
2015-04-15 14:30:27 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
class ConditionalGetApiTest < ActionController::TestCase
|
|
|
|
tests ConditionalGetApiController
|
|
|
|
|
|
|
|
def setup
|
|
|
|
@last_modified = Time.now.utc.beginning_of_day.httpdate
|
|
|
|
end
|
|
|
|
|
2015-05-05 14:15:15 -04:00
|
|
|
def test_request_gets_last_modified
|
2015-04-15 14:30:27 -04:00
|
|
|
get :two
|
2016-08-06 12:54:50 -04:00
|
|
|
assert_equal @last_modified, @response.headers["Last-Modified"]
|
2015-04-15 14:30:27 -04:00
|
|
|
assert_response :success
|
|
|
|
end
|
|
|
|
|
2015-05-05 14:15:15 -04:00
|
|
|
def test_request_obeys_last_modified
|
2015-04-15 14:30:27 -04:00
|
|
|
@request.if_modified_since = @last_modified
|
|
|
|
get :two
|
|
|
|
assert_response :not_modified
|
|
|
|
end
|
|
|
|
|
|
|
|
def test_last_modified_works_with_less_than_too
|
|
|
|
@request.if_modified_since = 5.years.ago.httpdate
|
|
|
|
get :two
|
|
|
|
assert_response :success
|
|
|
|
end
|
|
|
|
|
|
|
|
def test_request_not_modified
|
|
|
|
@request.if_modified_since = @last_modified
|
|
|
|
get :one
|
|
|
|
assert_equal 304, @response.status.to_i
|
|
|
|
assert @response.body.blank?
|
2016-08-06 12:54:50 -04:00
|
|
|
assert_equal @last_modified, @response.headers["Last-Modified"]
|
2015-04-15 14:30:27 -04:00
|
|
|
end
|
|
|
|
end
|