Search code examples
ruby-on-rails-5rspec-rails

How would I mock `request.xhr?` in a Rails 5 helper spec?


I'm testing Rails 5 helpers in rspec. We have a block in a helper which is wrapped in a conditional:

if request.xhr?
  # do stuff
end

In the specs, I'm unable to force that request.xhr? test to return true. I've tried allow_any_instance_of(ActionController::Request).to receive(:xhr?).and_return(true) but that says Undefined Constant ActionController::Request (which sort of makes sense). I also tried allow(request).to receive(:xhr?).and_return(true) but that just failed silently.

How can I test this - both that the #do stuff code is executed when we want it to be, and that it does what we expect?


Solution

  • The answer turned out to be allow_any_instance_of(ActionDispatch::Request).to receive(:xhr?).and_return(true). I had missed that the Request object had moved out of the ActionController module and into ActionDispatch.