If your controller action looks like this:
respond_to do |format|
format.html { raise \'Unsupported\' }
format.js # index.js.erb
end
and yo
Use code like this for parameters and user id, etc., notice that format option is in the same hash of other parameters like id and nested_attributes.
put :update, {id: record.id, nested_attributes: {id: 1, name: "John"}, format: :js}, user.id
I had similar problem:
# controller
def create
respond_to do |format|
format.js
end
end
# test
test "call format js" do
record = promos(:one)
post some_url(record)
assert true
end
and the result was this:
> rails test
Error:
ActionController::UnknownFormat: ActionController::UnknownFormat
I fixed it with this adjusting to the test(adding headers):
test "call format js" do
record = promos(:one)
headers = { "accept" => "text/javascript" }
post some_url(record), headers: headers
assert true
end
rails (6.0.0.beta3)
Many of the above answers are outdated.
The correct way to do it in RSpec 3+ is post some_path, xhr: true
.
Deprecation warning straight from RSpec itself, when attempting to use xhr :post, "some_path"
:
DEPRECATION WARNING: `xhr` and `xml_http_request` are deprecated and will be removed in Rails 5.1.
Switch to e.g. `post comments_path, params: { comment: { body: 'Honey bunny' } }, xhr: true`.
Also, xhr :post, "some_path"
results in some funky errors that doesn't happen with post some_path, xhr: true
.
with rspec:
it "should render js" do
xhr :get, 'index'
response.content_type.should == Mime::JS
end
and in your controller action:
respond_to do |format|
format.js
end
Use this before request:
@request.env['HTTP_ACCEPT'] = 'text/javascript'
These three seem to be equivalent:
get :index, :format => 'js'
@request.env['HTTP_ACCEPT'] = 'text/javascript'
@request.accept = "text/javascript"
They cause the controller to use a js template (e.g. index.js.erb)
Whereas simulating an XHR request (e.g. to get a HTML snippet) you can use this:
@request.env['HTTP_X_REQUESTED_WITH'] = "XMLHttpRequest"
This means request.xhr? will return true.
Note that, when simulating XHR, I had to specify the expected format or I got an error:
get :index, format: "html"
Tested on Rails 3.0.3.
I got the latter from the Rails source, here: https://github.com/rails/rails/blob/6c8982fa137421eebdc55560d5ebd52703b65c65/actionpack/lib/action_dispatch/http/request.rb#L160