RSpecでRedmineのsudoモードをテストする


# spec/support/time_helpers.rb
RSpec.configure do |config|
  # travel_toを使えるようにする
  # https://api.rubyonrails.org/classes/ActiveSupport/Testing/TimeHelpers.html#method-i-travel_to
  config.include ActiveSupport::Testing::TimeHelpers, type: :feature
end
RSpec.describe 'sudoモードが有効になっているとパスワードを入力しないと操作ができない', type: :feature do
  include ActiveSupport::Testing::TimeHelpers

  background do
    # sudoモードを有効にする
    allow(Redmine::SudoMode).to receive(:enabled?).and_return(true)
  end

  scenario '操作しようとしたらsudoモードの期限が切れていたのでパスワードを再入力して操作を完了する' do
    visit パスワードの再入力が求められるフォームがある_path
    fill_in 'パスワードの再入力が求められるフィールド', with: 'なにか'

    # Redmine::SudoMode.timeoutの値はデフォルトだと15分に設定されている。
    # そのため20分後に操作をしてパスワードの再入力が求められることを確認する。
    travel_to(20.minutes.from_now) do
      click_on '送信'
      expect(page).to have_content('この操作を続行するにはパスワードを入力してください')
      fill_in 'パスワード', with: 'password'
      click_on '送信'
    end

    expect(page).to have_content('操作が成功した際に表示されるであろう文言')
  end
end

参考

https://github.com/redmine/redmine/blob/f0d579adebfe3c5da93135fbaa3d9ec503d06855/test/integration/sudo_mode_test.rb#L9
https://github.com/redmine/redmine/blob/f0d579adebfe3c5da93135fbaa3d9ec503d06855/test/integration/sudo_mode_test.rb#L197-L200