Skip to content

Instantly share code, notes, and snippets.

@maxcal
Forked from ismasan/gist:8217804
Last active March 30, 2019 01:53
Show Gist options
  • Save maxcal/8e7e0ee4ff83a3ad0c8a to your computer and use it in GitHub Desktop.
Save maxcal/8e7e0ee4ff83a3ad0c8a to your computer and use it in GitHub Desktop.
Rspec examples for HTTP caching
# Given a controller that looks like this
class ModelsController < ApplicationController
load_and_authorize_resource #CanCan
def show
if stale? @model
respond_to do |format|
format.json do
@model
end
end
end
end
end
# The spec looks like this
context "http caching" do
context "given a model" do
before do
@model = Factory :model, :user => @brett
end
context "on the first request" do
it "returns a 200" do
get :show, :id => @model.id, :format => :json
expect(response.code).to eq "200"
end
it "sends 'ETag' header" do
expect(response.headers['ETag']).to be_present
end
it "sends 'Last-Modified' header" do
expect(response.headers['Last-Modified']).to be_present
end
end
context "on a subsequent request" do
before do
get :show, :id => @model.id, :format => :json
@etag = response.headers['ETag']
@last_modified = response.headers['Last-Modified']
end
context "if it is not stale" do
before do
request.env['HTTP_IF_NONE_MATCH'] = @etag
request.env['HTTP_IF_MODIFIED_SINCE'] = @last_modified
end
it "returns a 304" do
get :show, :id => @model.id, :format => :json
expect(response.code).to eq "304"
end
end
context "if it has been updated" do
before do
sleep 1 # To ensure the model.updated_at has a delta of at least 1 sec
@model.touch
request.env['HTTP_IF_NONE_MATCH'] = @etag
request.env['HTTP_IF_MODIFIED_SINCE'] = @last_modified
end
it "returns a 200" do
# Initialize account_item instance in the controller so CanCan
# will load up the resource from the db again
controller.instance_variable_set(:@model, nil)
get :show, :id => @model.id, :format => :json
expect(response.code).to eq "200"
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment