[Java] [Rails] JavaScript-related tests

1 minute read

Introduction

In the test with Capybara, you need to change the setting a little if you want to process JavaScript. As a simple example, let’s test the process of changing the text when clicked.

36a2e16cd12c7ebb3b25be633051a96a.gif Rails version uses 5.2.3.

Configuration

First you need to install Capybara, but if you do not understand it, please refer to this article written in the past.

Next, add to the helper file.

spec_helper.rb


# Add to the last line
ENV["RAILS_ENV"] ||='test'
require File.expand_path("../../config/environment", __FILE__)
Capybara.javascript_driver = :selenium_chrome_headless

*For some reason, using webkit for javascript_driver didn’t work… If you are familiar with this, it would be helpful if you could comment.

test file

Prepare the files under spec/features.

sample_spec.rb


require'rails_helper'

feature'post', type: :feature do

  scenario'js works', js: true do
# Click display exists
    visit root_path
    expect(page).to have_content ('click')

# Click on the click characters to go OK
    find('.js-class').click
    expect(page).to have_text("OK")
  end
end

If you want js to work, you need to add js: true to the scenario line as described above.

The view file and js file are also posted just in case. (I use Haml and jQuery)

haml:index.html.haml


.header
  = link_to "top page", root_path
.js-class
  click

sample.js


$(function(){
  $(".js-class").on("click", function() {
    $(this).text("OK");
  })
})

Test execution

All you have to do is execute it from the terminal.

terminal


$ bundle exec rspec spec/features/sample_spec.rb

fcbc5bed345b38c37a9394684c68513a.png The test has passed successfully.