How to write a remote request spec?

Viewed 947

I've got an action in my rails app that responds both in html and js format. The result, according to the format, changes a bit. So I'd like to write one test for html and other for js response. I'm using rspec.

Controller:

# app/controllers/my_controller.rb
class MyController < ApplicationController
  def my_action
    respond_to do |format|
      format.html do
        # Do something...
      end

      format.js do
        # Do something else...
      end
    end
  end
end

Spec:

# spec/requests/my_spec.rb
require "rails_helper"

RSpec.describe "My", type: :request do
  describe "GET /my_action" do
    context 'HTML' do
      # HTML tests
    end

    context 'JS' do
      # JS tests
    end
  end
end
1 Answers

Rails detects request format via http Accept header, in tests there's a helper for simulating xhr (also sets X-Requested-With, which is part of CSRF mitigation):

get "/some/path/to/my_action", xhr: true
Related