ruby-on-railsrspecruby-on-rails-6trixactiontext

How to test ActionText using RSpec?


I am trying to write an RSpec system test that involves filling out an ActionText / Trix field on a page.

It seems as though ActionText::SystemTestHelper as defined here is available to help with this task but so far I have not had any success in implementing it.

My RSpec test looks like the following:

# spec/system/add_job_posting_spec.rb

require 'rails_helper'

RSpec.describe 'adding a job posting', type: :system do
  let(:user) { FactoryBot.create :user }

  before do
    login_as(user)
    visit new_job_posting_path
  end

  context 'with valid information' do
    let(:valid_job_posting) { FactoryBot.create :job_posting }

    scenario 'creates a job posting', js: true do
      fill_in 'Title', with: valid_job_posting.title
      fill_in_rich_text_area 'Description', with: 'Job Info'

      click_button 'Submit'
      expect(page).to have_content 'Job was successfully created.'
    end
  end
end

I have also tried to create a RSpec support file as such

# spec/support/action_text.rb

RSpec.configure do |config|
  config.include ActionText::SystemTestHelper, type: :system
end

When I run this using

bundle exec rspec spec/system/add_job_posting_spec.rb

I get the following error uninitialized constant ActionText::SystemTestHelper

When I try to remove the file located at spec/support/action_text.rb I get this error instead:

undefined method `fill_in_rich_text_area'

I have also tried to just use the regular fill_in RSpec method to avoid that entirely but then get:

Unable to find field "Description" that is not disabled

Despite the fact that the test is marked as js: true and I have another RSpec support file to handle that which is setup as follows:

# spec/support/system/driver.rb

RSpec.configure do |config|
  config.before(:each, type: :system) do
    driven_by :rack_test
  end

  config.before(:each, type: :system, js: true) do
    ActiveRecord::Base.establish_connection
    driven_by :selenium_chrome_headless
  end
end

Solution

  • Here’s the script I’m using (just include it as a helper):

    def fill_in_trix_editor(id, with:)
      find(:css, "##{id}").click.set(with)
    end
    

    ActionText creates an underscored id of the model + attribute. You can also inspect to see.