Last active
April 6, 2021 15:02
-
-
Save arnab/3749227 to your computer and use it in GitHub Desktop.
Allow & test CORS requests in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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... |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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