Rails-ujs doesn't work in Capybara tests in Rails 7 (with Selenium driver)

958 Views Asked by At

I've connected @rails/ujs, pinned it and included in js files. And I see that code works as I expect, when I try to do it on development server. But when I launch my capybara tests with selenium driver, I see in logs, that form (which has remote: true flag) submitted as HTML.

Here is my code:

views/articles/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 

app/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)
  }
}

articles_controller.rb

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

articles/index.js.erb

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

container = document.getElementById('articles')

container.innerHTML = articlesTable

spec/acceptance/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

...

And when I launch some js file on the page (for example, send AJAX requests), I see them in test logs, therefore I see, that selenium driver works. I think, I've connected rails-ujs not properly, but not sure, what exactly I have missed. Can anyone help please? Thank you very much in advance!

1

There are 1 best solutions below

1
Thomas Walpole On

If it works in development env but not in test env you most likely have an error in one of your JS files. In the development mode each JS file is loaded separately so an error in one won't affect the others. However, in test (and production) mode the files are concatenated together which means an error in one JS file can prevent others from running. Check your browser logs in development mode for JS errors and fix them.