代码之家  ›  专栏  ›  技术社区  ›  RailsJohn

水豚复选框不触发JS?

  •  0
  • RailsJohn  · 技术社区  · 7 年前

    我试图测试以下表单,该表单允许用户通过选中复选框来隐藏其个人资料。

    <%= 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
    

    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 ==)
    

    非常感谢您的帮助,了解这可能不起作用的原因。。

    我添加了一个flash通知,当选中/取消选中复选框时显示。

      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')
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Thomas Walpole    7 年前

    account 因此 hidden

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

    然而,由于操作(勾选/取消勾选/单击等)不能保证等待它们触发的任何行为,因此很可能在预期运行时表单提交不会完成(因此对象没有更新)(因此在功能规范中通常不赞成对数据库对象的预期)。如果您的页面在表单提交完成时发生了可见的更改,那么您应该在检查数据库对象之前设置一个期望值,或者更好的做法是跳过测试数据库对象,而是测试用户实际看到的内容,即在选中该框后隐藏他们的配置文件。