Skip to content

Instantly share code, notes, and snippets.

@arnab
Last active April 6, 2021 15:02
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnab/3749227 to your computer and use it in GitHub Desktop.
Save arnab/3749227 to your computer and use it in GitHub Desktop.
Allow & test CORS requests in Rails
before_filter: allow_cors_requests
def allow_cors
headers["Access-Control-Allow-Origin"] = "*"
headers["Access-Control-Allow-Methods"] = %w{GET POST PUT DELETE}.join(",")
headers["Access-Control-Allow-Headers"] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(",")
head(:ok) if request.request_method == "OPTIONS"
# or, render text: ''
# if that's more your style
end
shared_examples_for "any request" do
context "CORS requests" do
it "should set the Access-Control-Allow-Origin header to allow CORS from anywhere" do
response.headers['Access-Control-Allow-Origin'].should == '*'
end
it "should allow general HTTP methods thru CORS (GET/POST/PUT/DELETE)" do
allowed_http_methods = response.header['Access-Control-Allow-Methods']
%w{GET POST PUT DELETE}.each do |method|
allowed_http_methods.should include(method)
end
end
# etc etc
end
end
describe "HTTP OPTIONS requests" do
# With Rails 4 (currently in master) we'll be able to `options :index`
before(:each) { process :index, nil, nil, nil, 'OPTIONS' }
it_should_behave_like "any request"
it "should be succesful" do
response.should be_success
end
end
# And similar tests for GET/POST what have you which actually test the functionality...
response.headers['Access-Control-Allow-Origin'].should == '*'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment