rspec测试更新ajax按钮

I want to test an AJAX update button with rspec but I don't know exactly how to do it. I used the M. Hartl Tutoriel but it didn't worked out :

Here is my app/views/products/buttons/_givable.html.erb :

<div class="status_button givable_button" id="givable_button_<%=product.id%>">
  <% if product.givable? %>
    <%= form_for(product, remote: true) do |f| %>
      <div><%= f.hidden_field :givable, value: nil %></div>
      <%= f.submit t('product.givable.undo'), class: "btn btn-success btn-small" %>
    <% end %>
  <% else %>
    <%= form_for(product, remote: true) do |f| %>
      <div><%= f.hidden_field :givable, value: true %></div>
      <%= f.submit t('product.givable.do'), class: "btn btn-small" %>
    <% end %>
  <% end %>
</div>

Here is my app/controllers/product.rb :

def update
  @product = Product.find(params[:id])
  @user = current_user
  if @product.update_attributes(product_params)
    respond_to do |format|
      format.html do
        flash[:success] = t('flash.success.product.update')
        redirect_to @product
      end
      format.js
    end
  else
    render 'edit'
  end
end

Here is my app/views/products/update.js.erb :

$("#givable_button_<%=@product.id%>").html("<%= escape_javascript(render('products/buttons/givable', product: @product)) %>")

And here is my test :

  describe "updating a product to unsharable with Ajax" do

    it "should increment the unsharable product count" do
      expect do
        xhr :patch, :update, id: product.id
      end.to change(Product.where(sharable: nil), :count).by(1)
    end

    it "should decrement the sharable product count" do
      expect do
        xhr :patch, :update, id: product.id
      end.to change(Product.where(sharable: true), :count).by(-1)
    end

  end

Then the answer :

Failure/Error: expect do
   count should have been changed by -1, but was changed by 0

It is clearly your second rpec example had some problem.

it "should decrement the sharable product count" do
  expect do
    xhr :patch, :update, id: product.id
  end.to change(Product.where(sharable: true), :count).by(-1)
end

Instead of,

xhr :patch, :update, id: product.id

I think it should be,

xhr :delete, :destroy, id: product.id

Try this and see what happens.