超簡単なモデルの単体テストをやってみる。
前回せっかくミニアプリまで作ったので、今までまともにやってこなかったモデルの単体テストもやってしまおう!
と、今回は、超簡単な単体テストを実施しました。
テスト環境の準備が色々あったので備忘録として記載します。
動作環境
ruby 2.5.1
rails 5.2.4.2
下準備
modelとかmigration等、ここまでの環境は前回記事の下準備をご覧ください。
テスト環境の準備
gemをインストール
..Gemfile
(以下を追記)
gem 'rspec-rails'
gem 'factory_bot_rails'
terminal.
$ bundle install
respecをインストール
terminal.
$ rails g rspec:install
.rspecへの追記
..rspec
(以下を追記)
--format documentation
これ、なんの意味があるのかと思ったら、書かないとターミナルにテスト結果がdocument形式で表示されません。
spec/rails_helper.rbへの追記
spec/rails_helper.rb
RSpec.configure do |config|
(以下を追記)
config.include FactoryBot::Syntax::Methods #Factory_botのメソッドを使用するため
end
rspecファイルを作成する
terminal.
$ bin/rails g rspec:model item
単体テスト実装
それでは単体テストのコードを書いていきます。
とりあえずテスト用インスタンスをつくってみた。
まずは半端な知識でテスト用のインスタンスを作ります。
spec/factoreis/item.rb
FactoryBot.define do
factory :item do
#name に "test" とだけ入れます。
name {"test"}
end
end
とりあえずテストコードも書いてみた。
次に半端な知識でテストコードも書いていきます。
spec/models/item_spec.rb
require 'rails_helper'
RSpec.describe Item, type: :model do
describe '#create' do
let(:item) {build(:item)}
context 'can save' do
it "is valid with a name" do
expect(item).to be_valid #name に "test" が入っていれば成功する(はず)
end
end
context 'can not save' do
it "is valid without a name" do
item.name = "" #name が 空の場合
expect(item).to be_invalid #失敗する(はず)
end
end
end
end
テストコード走らせてみた。
インスタンスも作った。テストコードも書いた。
次にやることと言ったら、もう決まってる。
いざ。
terminal.
$ bundle exec rspec spec/models/item_spec.rb
terminal.
Item
#create
can save
is valid with a title
can not save
is valid without a title (FAILED - 1)
Failures:
1) Item#create can not save is valid without a title
Failure/Error: expect(item).to be_invalid
expected `#<Item id: nil, title: "", created_at: nil, updated_at: nil>.invalid?` to return true, got false
# ./spec/models/item_spec.rb:14:in `block (4 levels) in <top (required)>'
Finished in 0.34277 seconds (files took 5.22 seconds to load)
2 examples, 1 failure
Failed examples:
rspec ./spec/models/item_spec.rb:12 # Item#create can not save is valid without a title
あれ? エラー?
あ、validation書いてないですねこれ。
validationを追加してみた。
null: false
だけ追加します。
app/models/item.rb
class Item < ApplicationRecord
(中略)
validates :name,presence: true #null: false
end
結果
terminal.
$ bundle exec rspec spec/models/item_spec.rb
terminal.
Item
#create
can save
is valid with a title
can not save
is valid without a title
Finished in 0.33208 seconds (files took 6.29 seconds to load)
2 examples, 0 failures
上手(?)にできました!
教訓
validationを忘れない!
今回は以上です。