4

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
Chiara Ani
  • 918
  • 7
  • 25

2 Answers2

2

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
Vasfed
  • 18,013
  • 10
  • 47
  • 53
0

You can try all the possible combinations of this:

put :update, params.merge(format: :js), xhr: true, format: :js, headers: { 'HTTP_ACCEPT' => 'text/javascript' }

and then remove one of the parameters to test to find the final one.

TorvaldsDB
  • 766
  • 9
  • 8