我想用 rspec 测试一个 AJAX 更新按钮,但我不知道该怎么做。我使用了M. Hartl Tutoriel但没有成功:
这是我的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>
这是我的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
这是我的app/views/products/update.js.erb:
$("#givable_button_<%=@product.id%>").html("<%= escape_javascript(render('products/buttons/givable', product: @product)) %>")
这是我的测试:
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
然后答案:
Failure/Error: expect do
count should have been changed by -1, but was changed by 0