Writing an RSpec test for CORS

March 6, 2021

I recently had to add CORS handling to an application. I used the rack-cors gem which made it somewhat easy. When it came to writing Rspec tests, I had difficulty figuring out how to how to structure it. This is what I came up with.

My config/initializers/cors.rb file has a section for www.example.com so all of the Rspec tests will pass.

                allow do
                  origins 'www.example.com'
                  resource '*',
                       headers: :any,
                       methods: [:get, :post, :put, :patch, :delete, :options, :head],
                       credentials: true

I wrote one test that passed CORS successfully and one that failed.

                RSpec.describe "CORS", type: :request do
                  it "allows the request" do
                    headers = { "HTTP_ORIGIN" => "http://www.example.com" }
                    post "/api/v1/opportunities", :headers => headers
                    expect(response.headers["Access-Control-Allow-Methods"]).to eq("GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD")
                    expect(response.headers["Access-Control-Allow-Origin"]).to eq('http://www.example.com')

                  it "denies the request" do
                    headers = { "HTTP_ORIGIN" => "http://www.badexample.com" }
                    post "/api/v1/opportunities", :headers => headers
                    expect(response.headers).not_to include("Access-Control-Allow-Methods")
                    expect(response.headers).not_to include("Access-Control-Allow-Origin")

These are basic tests that do not fully test the functionality, but it confirms that CORS is being handled. I also manually tested the implementation using fetch() and XHR.