Search code examples
ruby-on-railsrubyrspecstimulusjs

How to run StimulusJs with rspec


I have modal component, and inside the modal I have a form. The modal shows or hides using StimulusJs. When I render the modal component using turbo_stream, it executes the stimulus controller and shows it. However, when I am trying to test it using rspec, I see the content gets loaded through turbo_stream but it does not visually show it. I always get the following error:

Unable to find visible field "user[username]" that is not disabled within #<Capybara::Node::Element tag="div" path="/HTML/BODY[1]/TURBO-FRAME[1]/DIV[1]/DIV[3]/DIV[1]/DIV[3]">

Note that the content is not present on page load, only when a button is clicked it will load the modal component. I know this works because I have an expect for it after the button is clicked:

expect(page).to have_css("[data-controller='modal']")

But then when trying to run

fill_in("Username", with: "testing01")

I have tried different variations like find(#).set() but always with the error that the element is not visible.

describe "Username modal", type: :system do
  it "should change the username" do
    visit profile_path
    
    expect(page).to_not have_css("[data-controller='modal']")
    page.find("#change-username").click
    
    expect(page).to_not have_css("[data-controller='modal']")
    fill_in("Username", with: "testing01") # <--- Error mentioned above
    page.find("#submit-change-username").click
    
    expect(page).to have_text("Username changed!")
  end
end

This makes me think that StimulusJS is not running. Is there anything I have to do to make sure it runs in rspec?


Solution

  • For future reference, I realized that I needed to precompile the assets for the tests to grab the latest changes. I ended up running: rails assets:clobber assets:precompile. Then, I restarted the server, ran the tests gain, and it worked.