クレジット決済ミニアプリ実装について

その2テストコードを実装

RSpecとFactoryBotのGemを導入

Gemfileに以下を追記しましょう。:development, :testと指定するグループ内に記述すること

# 省略

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'rspec-rails'
  gem 'factory_bot_rails'
end

# 省略

rspec gemを導入

USERnoMacBook-puro:payjp_practice user$ bundle install
# 省略
Using webpacker 4.3.0
Bundle complete! 19 Gemfile dependencies, 80 gems now installed.
Use `bundle info [gemname]` to see where a bundled gem is installed.
USERnoMacBook-puro:payjp_practice user$

Rspecをインストール

USERnoMacBook-puro:payjp_practice user$ rails g rspec:install
Running via Spring preloader in process 49554
      create  .rspec
      create  spec
      create  spec/spec_helper.rb
      create  spec/rails_helper.rb
USERnoMacBook-puro:payjp_practice user$ 

.rspecの設定ファイルに、テストコードの実行ログが見やすくなるため

--require spec_helper
--format documentation # ←こちらを記述!

Orderモデルの単体テストコードを記述するspecファイルを生成

USERnoMacBook-puro:payjp_practice user$ rails g rspec:model order
Running via Spring preloader in process 49604
      create  spec/models/order_spec.rb
      invoke  factory_bot
      create    spec/factories/orders.rb
USERnoMacBook-puro:payjp_practice user$ 

FactoryBotでデータを生成

FactoryBot.define do
  factory :order do
    price {3000} #←こちらを記述
  end
end

テストコードを実装

require 'rails_helper'

RSpec.describe Order, type: :model do
  pending "add some examples to (or delete) #{__FILE__}"#←こちらを削除
  before do
    @order = FactoryBot.build(:order) # インスタンスを生成
  end

  context '内容に問題ない場合' do  
    it "priceがあれば保存ができること" do # example1
      expect(@order).to be_valid
    end
  end

  context '内容に問題がある場合' do 
    it "priceが空では保存ができないこと" do # example2
      @order.price = nil
      @order.valid?
      expect(@order.errors.full_messages).to include("Price can't be blank")
    end
  end
end

テスト成功か確認

USERnoMacBook-puro:payjp_practice user$  bundle exec rspec spec/models/order_spec.rb 

Order
  内容に問題ない場合
    priceがあれば保存ができること
  内容に問題がある場合
    priceが空では保存ができないこと

Finished in 0.0213 seconds (files took 1.21 seconds to load)
2 examples, 0 failures # ← 成功した

USERnoMacBook-puro:payjp_practice user$ 

未経験でのWebエンジニア転職を目指して、プログラミングを学習しています。日々の学習した内容をアウトプット用にはてなを書き始めました。TECH CAMP 102 期学生