0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[RSpec] binding.pry 単体テストコードの基本用法

Last updated at Posted at 2021-01-04

はじめに

メモ用に記録しています。
特に何かを参考したわけではありませんので、間違いはご指摘いただけると幸いです。

テストコード実行コマンド
bundle exec rspec テストするファイル名 ←# spec/から記述

spec/factories/orders.rb
FactoryBot.define do
  factory :order do
    price { 3000 }
  end
end
spec/models/order_spec.rb
require 'rails_helper'

RSpec.describe Order, type: :model do
  before do
    @order = FactoryBot.build(:order)
  end

  describe '購入情報のデータの保存' do
    context '成功' do
      it "priceがあれば保存ができること" do
        expect(@order).to be_valid
      end
    end

    context '失敗' do
      it "priceが空では保存ができないこと" do
        @order.price = nil
        @order.valid?
        expect(@order.errors.full_messages).to include("Price can't be blank")
      end
    end
  end
end

基本用法

FactoryBotのインスタンスが正しく生成されているか?
インスタンス変数に代入されているか?
を確認します。

spec/models/order_spec.rb
RSpec.describe Order, type: :model do
  before do
    @order = FactoryBot.build(:order)
    binding.pry  
  end

Image from Gyazo

price: 3000
という値が@orderに含まれていることがわかりました。
FactoryBotのインスタンス生成は成功です。


インスタンス変数に値は入っているか?
バリデーションを通してエラーがあるかどうか?
を確認します。

spec/models/order_spec.rb
describe '購入情報のデータの保存' do
    context '成功' do
      it "priceがあれば保存ができること" do
        expect(@order).to be_valid
        binding.pry  
      end
    end

Image from Gyazo
@order.valid? の結果が trueとなっています。
「priceがあれば保存ができること」というテストは成功です。


インスタンス変数に値は入っているか?
バリデーションを通してエラーがあるかどうか?
エラーメッセージの内容は?
を確認します。

spec/models/order_spec.rb
context '失敗' do
      it "priceが空では保存ができないこと" do
        @order.price = nil
        @order.valid?
        expect(@order.errors.full_messages).to include("Price can't be blank")
        binding.pry  
      end
    end

Image from Gyazo
インスタンス変数の中身が、代入した price: nil になっています。
これにより@order.valid?の結果は false になり、
エラーメッセージは "Price can't be blank" であることが確認できました。

「priceが空では保存ができないこと」というテストは成功です。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?