LoginSignup
2
1

More than 3 years have passed since last update.

Rspecを動かすまでまとめ(簡易版: 単体・統合テスト)

Posted at

今回はテスト内容などにはあまり触れていません
Rspecを使ってテストするまでをまとめています。

Gemfile
group :test do
  gem 'capybara'
  gem 'rspec-rails'
  gem "factory_bot_rails"
  gem 'faker'
end

group :test do 〜 endの中を変更し、bundle install します。

ターミナル
$ bundle install
$ rails g rspec:install
spec/rails_helper.rb

 #最後の方に追加する
 config.include FactoryBot::Syntax::Methods
end

記述することでletを使用した際に、FactoryBotが使用できるようになります。

factories/item.spec.rb
FactoryBot.define do
  factory :"モデル名" do
    "カラム名" { Faker::Lorem.characters(number: 10) }
  end
end

Faker::Lorem.characters(number: 10)とは
テスト用の文字列を作成する。今回の場合はカラム名のところに10文字のテストデータを作成してくれます。

spec_helper.rb
RSpec.configure do |config|
  #追加します
  config.before(:each, type: :system) do
    driven_by :rack_test
  end

#省略
end

単体テスト

models/item_spec.rb

require 'rails_helper'

RSpec.describe 'Itemモデルのテスト', type: :model do
  describe 'バリデーションのテスト' do
    subject { item.valid? }

    let(:user) { create(:user) }
    let(:genre) { create(:genre) }
    let!(:item) { build(:item, user_id: user.id, genre_id: genre.id) }

    context 'nameカラム' do
      it '空でないこと' do
        item.name = ''
        is_expected.to eq false
      end
      it '2文字以上であること: 2文字は〇' do
        item.name = Faker::Lorem.characters(number: 2)
        is_expected.to eq true
      end
      it '2文字以上であること: 1文字は×' do
        item.name = Faker::Lorem.characters(number: 1)
        is_expected.to eq false
      end
    end
  end
end
ターミナル
$ rspec spec/models/item_spec.rb

単体テストの実行できます。
今回はItemモデルのテスト実行しています。

統合テスト

system/test.spec.rb
require 'rails_helper'

 describe 'トップ画面のテスト' do
   before do
     visit root_path
   end

   context '表示内容の確認' do
     it 'URLが正しい' do
        expect(current_path).to eq '/'
     end
   end
 end

ターミナル
$ rspec spec/system/test.spec.rb

統合テストの実行できます。

これでテスト環境は出来ましたので
追加したい項目を書いていくだけになります。

おまけ

system/test_spec.rb
let(:"モデル名") { FactoryBot.create(:"モデル名", "カラム名": "データ") }
let(:item) { create(:item, user_id: user.id, genre_id: genre.id) }

2個目の記述のようにFactoryBotを省略できます。

letとlet!の違い

item_spec.rb
let(:genre) { create(:genre) }
let!(:item) { build(:item, user_id: user.id, genre_id: genre.id) }
  • letを使用した場合は処理が行われずにitの中で呼ばれたときにcreateが実行されます。
  • let!を使用した場合はそのまま処理される。
    毎回呼び出す必要のないものは" ! "を外した方がわかりやすくなります。

createとbuildの違い

item_spec.rb
let(:genre) { create(:genre) }
let!(:item) { build(:item, user_id: user.id, genre_id: genre.id) }
  • createはにメモリにデータを保存する。
  • buildはDBにデータ保存する。
使い分け方

今回はアイテムを登録するためのバリデーションをテストしますので
createで実行すると一回でもテストに通るとメモリに残っているので
アイテムが登録されている状態でバリデーションのテスト行うようになってしまうため、
ちゃんとテストが実行されているかが判断できなくなります。
これから確認したい対象物にはbuildを使うことがいいと思います。

2
1
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
2
1