3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【RSpec】テストの際、日付・時刻フォーム(datetime_select)に値を入力する

Last updated at Posted at 2019-10-27

参考サイト:https://gist.github.com/lbspen/5674563

はじめに

Capynaraを用いて、RSpecテストの際日付時刻フォームに値を入力する方法をメモします。
フォームに入力するためのヘルパーを定義し、それをRSpecで利用する、という方法をとります。

実行環境

この記事は以下の環境で動作確認しています。
ruby (2.3.7)
rails (5.2.3)
capybara(3.15.1)
rspec-rails(3.8.2)

ヘルパーの作成

ビュー側で、

<%= f.label :start_at, "開始時間" %>
<%= f.datetime_select :start_at %>

上記のフォームを定義すると、
id="モデル名_start_at_1i" (年を入力)
id="モデル名_start_at_2i" (月を入力)
id="モデル名_start_at_3i" (日を入力)
id="モデル名_start_at_4i" (時を入力)
id="モデル名_start_at_5i" (分を入力)
というIDを持つフィールドが作成されます。それぞれのフィールドに値を入力するようなヘルパーを以下のように作成します。

spec/support/select_date_helper.rb
module SelectDateHelpers
  def select_date(date, options = {})
    field = options[:from]
    base_id = find(:xpath, ".//label[contains(.,'#{field}')]")[:for]
    year, month, day = date.split(',')
    select year,  :from => "#{base_id}_1i"
    select month, :from => "#{base_id}_2i"
    select day,   :from => "#{base_id}_3i"
  end

  def select_time(hour, minute, options = {})
    field = options[:from]
    base_id = find(:xpath, ".//label[contains(.,'#{field}')]")[:for]
    select hour, :from => "#{base_id}_4i"
    select minute, :from => "#{base_id}_5i"
  end
end

rails_helperで以下のコードがコメントインされていることを確認します

spec/rails_helper.rb
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

さらに、上で作成したヘルパーをincludeします

spec/rails_helper.rb
RSpec.configure do |config|  
  
  config.include SelectDateHelpers
end

ヘルパーの利用

作成したヘルパーを、RSpecテストで利用します。
以下のように書くことで、前述の入力フォームに日付、時刻を入力できます。

select_date("2019,9,28", from: "開始時間")
select_time("13", "00", from: "開始時間")

これで、開始時間のフォームに 2019年9月28日13時00分 が入力されたことになります。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?