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(model)の読みやすい書き方

Last updated at Posted at 2021-05-15

#Rubyでテストを書くにあたって:point_up:
コメントにてご指摘をいただき、
Rspecをrailsなしで、ruby上で使うための設定方法を調べてみました。
https://stackoverflow.com/questions/12307097/how-to-use-rspec-without-rails

##userモデル
今回はこちらのメソッドへのテストの書き方について!

user.rb

class User
  def fullname
    [name, surname].join(' ') if middle_name.nil?
    [name, middle_name, surname].join(' ') if middle_name.nil?
  end
end

##userモデルRspec
userの名前が定義されている状況に応じて異なるフルネームを返す。

user_spec.rb

 describe 'fullname' do

    context 'with surname and name' do
      let(:user) { build(:user, surname: 'delicious', name: 'banana') }

      it 'shows full name without middle name' do

        expect(user.fullname).to eq('banana delicious')
        
      end
    end

    context 'with surname, name and middle name' do
      let(:user) { build(:user, surname: 'delicious', name: 'banana', middle_name: 'super') }

      it 'shows full name with middle name' do

        expect(user.fullname).to eq('banana super delicious')
        
      end
    end
  end

#どこに何を書けば良い?:writing_hand:
describe: メソッド名
context: 状況設定
it: returnされる結果

describe後にメソッド名のみを記載する事で、
後にテストを探す際、"describe 'メソッド名'"で探すと瞬時に見つけることができ、便利になります。

改善のアドバイス等ある方はコメントいただけると嬉しいです!:pray:

0
0
1

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?