[Ruby] [Rails] Method to define macros in Rspec and standardize processing

less than 1 minute read

Target

Standardize login process.

Development environment

・Ruby: 2.5.7 Rails: 5.2.4 ・Rspec-rails: 4.0.1 ・Vagrant: 2.2.7 ・VirtualBox: 6.1 ・OS: macOS Catalina

Implementation

1. Create a support directory

$ mkdir support

2. Create a file in the support directory and edit it

$ touch spec/support/login_macros.rb

login_macros.rb


module LoginMacros
  def login(user)
    fill_in'email address', with: user.email
    fill_in'password', with: user.password
    click_button'Login'
  end
end

3. Edit rails_helper.rb

rails_helper.rb


# Comment out line 23
Dir[Rails.root.join('spec','support','**','*.rb')].sort.each {|f| require f}

RSpec.configure do |config|
  config.include LoginMacros # Added
end

[Explanation]

① Read the support directory.

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

② Make the module defined in 2 available.

config.include LoginMacros

4. Using method

require'rails_helper'

RSpec.describe'Authentication test', type: :feature do
  let(:user) {create(:user)}
  subject {page}

  describe'Test user authentication' do
    context'User login test' do
      it'Be able to log in' do
        visit new_user_session_path
        use login(user) # method
        is_expected.to have_content'Logout'
      end
    end
  end
end