0

我已经连接了@rails/ujs,将其固定并包含在 js 文件中。当我尝试在开发服务器上执行此操作时,我看到该代码按预期工作。但是当我使用 selenium 驱动程序启动我的 capybara 测试时,我在日志中看到该表单(具有remote: true标志)作为 HTML 提交。

这是我的代码:

意见/文章/index.html.slim

= form_tag root_path, method: :get, remote: true, data: { controller: 'forms', forms_target: "form" }, id: :search_form  do
  = label_tag :query, t('artiles.search')
  = text_field_tag :query, nil, placeholder: t('articles.enter_your_search_query_here'),  data: { action: "input->forms#search" }
  = submit_tag t('buttons.find')

#articles
  = render 'articles', articles: @articles 

应用程序/javascript/controllers/forms_controller.js

import { Controller } from "@hotwired/stimulus"
import Rails from "@rails/ujs";

export default class extends Controller {
  static targets = [ "form" ]

  search() {
    clearTimeout(this.timeout)
    this.timeout = setTimeout(() => {
      Rails.fire(this.formTarget, 'submit')
    }, 200)
  }
}

文章控制器.rb

class ArticlesController < ApplicationController
  def index
    @articles = Article.where(
      'title LIKE :query OR body LIKE :query',
      query: "%#{params[:query]}%"
    )
  end

文章/index.js.erb

articlesTable = '<%= j(render 'articles', articles: @articles) %>';

container = document.getElementById('articles')

container.innerHTML = articlesTable

规范/接受/index_page_spec.rb

...

  context 'when user fills search form with existing value', js: true do
    before do
      fill_in 'query', with: target_article.title
      find("input[name='commit']").click
    end

    it "User sees only target article on the page" do
      (articles - [target_article]).map(&:title).each do |title|
        expect(page).not_to have_text(title)
      end

      expect(page).to have_text(target_article.title)
    end
  end

...

当我在页面上启动一些 js 文件(例如,发送 AJAX 请求)时,我会在测试日志中看到它们,因此我看到了 selenium 驱动程序工作。我想,我没有正确连接 rails-ujs,但不确定我到底错过了什么。有人可以帮忙吗?非常感谢您!

4

1 回答 1

0

如果它在开发环境中有效,但在测试环境中无效,则您的 JS 文件之一很可能有错误。在开发模式下,每个 JS 文件都是单独加载的,因此一个错误不会影响其他文件。然而,在测试(和生产)模式下,文件被连接在一起,这意味着一个 JS 文件中的错误可能会阻止其他文件运行。在开发模式下检查您的浏览器日志以查找 JS 错误并修复它们。

于 2022-01-19T16:33:54.483 回答