How to make an AJAX create or delete request to a nested resource in RSpec
Suppose you have a nested resource:
resources :photos do
resources :likes, only: [:create, :destroy]
end
Let's say that in your view clicking on a like button of a photo triggers an
AJAX request to the LikesController
. <!-- more --> The request either create
s a like if
the user hasn't likes the photo yet or destroy
s it. The urls must look like
this:
Verb | Action | Path
post
| create
| /photos/:photo_id/likes
delete
| destroy
| /photos/:photo_id/like/:id
In that case you need to construct a request in your specs which has the
following characteristics:
- be an AJAX request;
- be a
POST
orDELETE
request; - contain the photo id;
- contain the like id in the case of
destroy
.
So the create
requests will roughly look like that:
xhr :post, :create, photo_id: photo.id
where:
-
xhr
tellsRSpec
to make an AJAX request; -
:post
is the request verb; -
:create
is the controller action; -
photo_id
is the id of the photo the like must be created on. This assumes you have fabricated a photo and assigned it to the instance variablephoto
.
The destroy
request will be similar, but you also have to supply the like id:
xhr :delete, :destroy, photo_id: photo.id, id: like.id
It again assumes that you have fabricated a like and assigned it to like
.
Written by Alex Popov
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#