【问题标题】:How to test ActionText using RSpec?如何使用 RSpec 测试 ActionText?
【发布时间】:2019-12-10 16:21:59
【问题描述】:

我正在尝试编写一个涉及在页面上填写 ActionText / Trix 字段的 RSpec 系统测试。

似乎ActionText::SystemTestHelper 定义为here 可以帮助完成这项任务,但到目前为止我还没有成功实施它。

我的 RSpec 测试如下所示:

# 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

我也尝试过创建这样的 RSpec 支持文件

# spec/support/action_text.rb

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

当我使用

运行它时
bundle exec rspec spec/system/add_job_posting_spec.rb

我收到以下错误 未初始化的常量 ActionText::SystemTestHelper

当我尝试删除位于 spec/support/action_text.rb 的文件时,我得到了这个错误:

未定义方法 `fill_in_rich_text_area'

我也尝试只使用常规的fill_in RSpec 方法来完全避免这种情况,然后得到:

找不到未禁用的“描述”字段

尽管测试被标记为js: true 并且我有另一个 RSpec 支持文件来处理设置如下:

# 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

【问题讨论】:

    标签: ruby-on-rails rspec ruby-on-rails-6 trix actiontext


    【解决方案1】:

    spec/rails_helper.rb:

    需要帮助文件并将模块包含在系统规范中:

    require "action_text/system_test_helper"
    
    RSpec.configure do |config|
      config.include ActionText::SystemTestHelper, type: :system
    end
    
    

    您现在可以在系统规范中使用 fill_in_rich_text_area 助手:

    fill_in_rich_text_area "page_content", with: "Some content."
    

    ..."page_content" 是 trix-editor 的 ID。

    富文本区域也可以通过占位符属性的值、aria-label 属性的值、标签中的文本或输入的名称来找到。

    如果页面上只有一个编辑器,则可以省略第一个参数,如下所示:

    fill_in_rich_text_area with: "Some content."
    

    【讨论】:

      【解决方案2】:

      这是我正在使用的脚本(只需将其作为帮助程序包含在内):

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

      ActionText 创建模型 + 属性的下划线 id。也可以检查看看。

      【讨论】:

        【解决方案3】:

        我不是 100% 确定,但似乎 ActionText::SystemTestHelper 可能还没有发布到 Rails 的“稳定”版本中。它可能会与下一个一起出现(或者您可能正在运行尚未包含它的旧版本)。

        您可以尝试以下几种方法:

        • 更新 Rails 版本,看看是否有帮助
        • 使用来自 github 的当前 master Rails 版本(不推荐)
        • 自己添加模块作为规范的帮助模块,然后在需要的地方自己包含它

        【讨论】:

        • 这个助手现在包含在 Rails stable 中
        猜你喜欢
        • 2018-07-30
        • 2018-08-23
        • 2013-12-07
        • 2013-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-07
        • 2013-10-30
        相关资源
        最近更新 更多