[Rails] Test involving JavaScript

Introduction

In the test with Capybara, if you want to process JavaScript to work, you need to change the setting a little. This time, as a simple example, let's test the process of changing the text when clicked.

36a2e16cd12c7ebb3b25be633051a96a.gif The rails version is using 5.2.3.

Setting

First of all, you need to install Capybara, but if you do not understand, please refer to the this article that I wrote in the past.

Then add it to the helper file.

spec_helper.rb


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

Test file

Prepare the file under spec / features.

sample_spec.rb


require 'rails_helper'

feature 'post', type: :feature do

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

    #Click the click character and it will be 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.

Just in case, I also put the view file and js file. (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 run

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

Terminal


$ bundle exec rspec spec/features/sample_spec.rb
fcbc5bed345b38c37a9394684c68513a.png The test has passed successfully.

Recommended Posts

[Rails] Test involving JavaScript
Rails tutorial test
[Rails] Test with RSpec
rails test db only drop
[Rails] Test code using Rspec
[Rails] About Rspec response test
test
[Rails5] Rspec -Unit test when nesting-
[Rails] Unit test code for User model
[Ruby on Rails] View test with RSpec
JavaScript (vanilla) does not respond in Rails.
[Ruby on Rails] Controller test with RSpec
[Rails] Assigning variables from controller to JavaScript
[Ruby on Rails] Model test with RSpec