Tamarb Rspecモブプロ 〜共通メソッドをモジュールへ切り出す〜

本日はTamarbのRspecモブプロがあり、今回はfeature specを書き進めていきました。

以前と同様、エディタごとにチーム分けをし、自分は人数比的にRubyMineチームへ参加しました。

 

 

 

 知ったこと

1つのファイル内以外でも使いたいメソッドはモジュールに切り出すことでどのファイルでも共通で使うことができるようになります。

今回は以下のコードのサインイン部分(黄色部分)を切り出しました!

 

切り出す前

spec/feature/projets_spec.rb

require 'rails_helper'

RSpec.feature "Projects", type: :feature do
scenario "user creates a new project" do
user = FactoryBot.create(:user)

visit root_path
click_link "Sign in"
fill_in "Email", with: user.email

fill_in "Password", with: user.password
click_button "Log in"

expect {
click_link "New Project"
fill_in "Name", with: "Test Project"
fill_in "Description", with: "Trying out Capybara"
click_button "Create Project"

expect(page).to have_content "Project was successfully created"
expect(page).to have_content "Test Project"
expect(page).to have_content "Owner: #{user.name}"
}.to change(user.projects, :count).by(1)
end
end

 

 切り出した後

spec/feature/projets_spec.rb

require 'rails_helper'
require 'support/login_helper'

RSpec.feature "Projects", type: :feature do
include LoginHelper

scenario "user creates a new project" do
user = FactoryBot.create(:user)

sign_in(user)

expect {
click_link "New Project"
fill_in "Name", with: "Test Project"
fill_in "Description", with: "Trying out Capybara"
click_button "Create Project"

expect(page).to have_content "Project was successfully created"
expect(page).to have_content "Test Project"
expect(page).to have_content "Owner: #{user.name}"
}.to change(user.projects, :count).by(1)
end
end

 

 

切り出すにあたって、以下の設定や定義をしてあげます。

①spec/support/login_helper.rbへメソッド定義

spec/support/login_helper.rb

module LoginHelper
def sign_in(user)
visit root_path
click_link "Sign in"
fill_in "Email", with: user.email

fill_in "Password", with: user.password
click_button "Log in"
end
end

 

②spec/rails_helper.rbへlogin_helper.rbを読み込む設定追加

spec/rails_helper.rb

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
require 'capybara/rspec'
require 'support/login_helper'

 

 

感想その他

切り出して読み込む設定を追加して、、、等の処理を書くにあたってincludeやextend、requireが結構出てきました。メタプログラミングRuby少しでも読んでおいてよかったと思いました!

あと、vimチームがなんだかすごかったです。

vimチームの詳細は以下リンクが非常にわかりやすいです!

secret-garden.hatenablog.com