我已经连接了@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,但不确定我到底错过了什么。有人可以帮忙吗?非常感谢您!