如何使用 RSpec 测试 ActionText?

11

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

似乎可以使用在这里定义的ActionText :: SystemTestHelper来帮助完成此任务,但到目前为止,我还没有成功实现它。

我的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
3个回答

8
spec/rails_helper.rb 文件中:
需要引入帮助文件并在系统规格(spec)中包含该模块(module):
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。

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

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

fill_in_rich_text_area with: "Some content."

3
这是我使用的脚本(只需将其作为辅助程序包含即可):
def fill_in_trix_editor(id, with:)
  find(:css, "##{id}").click.set(with)
end

ActionText 创建了一个由模型和属性组成的下划线 id。您还可以进行检查。


0

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

你可以尝试以下几件事:

  • 更新Rails版本并查看是否有所帮助
  • 从github使用当前的 master Rails 版本(不推荐)
  • 将该模块自己添加为specs的helper module,然后在需要时自行包含

这个辅助工具现在已经包含在 Rails 稳定版中。 - developius

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接