水豚复选框不触发 JS?

Capybara checkbox not triggering JS?

我正在尝试测试以下表单,它允许用户通过选中复选框来隐藏他们的个人资料。

<%= form_tag toggle_hidden_path, id: 'toggle-form', method: :put, remote: true do %>
  <%= check_box_tag(:hide, value = '1', checked = @account_is_hidden) %>
<% end %>

选中或取消选中(更改)时,使用 JS 提交表单。

<script type="text/javascript">
  $('#hide').on('change', function() { $(this.form).submit(); });
</script>

我在模型中的控制器操作和方法切换:隐藏布尔值。

  # accountsController

  def toggle_hidden
    @account = current_user.account
    @account.toggle_hidden!
  end

  # account.rb

  def toggle_hidden!
   toggle!(:hidden)
  end

我正在使用 Rspec 和水豚。我的测试如下

require 'rails_helper'

feature 'Hide and show profile' do
  let(:account) {create :account}

  scenario 'successfully', js: true do
    login_as(account.user)
    visit dashboard_path

    expect(account.hidden).to eq(false)

    expect(page).to have_field('hide')
    check('hide')
    expect(page).to have_field('hide', checked: true)

    expect(account.hidden).to eq(true)
  end
end

测试错误;

Failures:

1) Hide and show profile successfully
 Failure/Error: expect(account.hidden).to eq(true)

   expected: true
        got: false

   (compared using ==)

对于为什么这可能不起作用的任何帮助,我们将不胜感激..

编辑

我添加了当复选框为 checked/unchecked 时显示的闪光通知。

  def toggle_hidden
   @account = current_user.account
   @account.toggle_hidden!
    respond_to do |format|
     format.js { flash[:notice] = "Hidden toggled" }
    end
  end

并更新了规范 - 但测试仍然没有通过。

expect(page).to have_content('Hidden toggled')

您已经加载了 account,因此对象中 hidden 的值不会改变。为了查看新值,您需要重新加载对象

expect(account.reload.hidden).to eq(true)

但是,由于不能保证操作 (check/uncheck/click/etc) 会等待它们触发的任何行为,所以表单提交很可能不会由您期望运行的时间(因此为什么在功能规范中通常不赞成对数据库对象的期望)。如果您的页面在表单提交完成后有明显的变化,您应该在检查数据库对象之前对此设置一个期望,或者更好的是跳过测试数据库对象,而是测试用户实际可以看到的内容——他们的个人资料是隐藏的在他们选中复选框后。