LoginSignup
0
0

More than 3 years have passed since last update.

Rspecの入門[簡易版](単体・統合テスト)

Last updated at Posted at 2021-03-30

modelのテスト(単体)

require 'rails_helper'

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

    let(:user) { create(:user) }
    let!(:(モデル名)) { build(:(モデル名), user_id: user.id) }

    context 'カラム' do
      it '空欄でないこと' do
        (モデル名).(カラム名) = ''
        is_expected.to eq false #falseが返ってきたらok
      end
    end

      it '100文字以下 :100文字は〇' do
        (モデル名).(カラム名) = Faker::Lorem.characters(number: 100)
                                                  #文字列100入れる
        is_expected.to eq true #trueが返ってきたらok
      end
      it '100文字以下 :101文字は×' do
        (モデル名).(カラム名) = Faker::Lorem.characters(number: 101)
                                                 #文字列101入れる
        is_expected.to eq false #falseが返ってきたらok
      end
    end
  end

  describe 'アソシエーションのテスト' do
    context 'Userモデルとの関係' do
      it 'N:1となっている' do
        expect((モデル名).reflect_on_association(:user).macro).to eq :belongs_to
      end
    end

    context '(モデル名)モデルとの関係' do
      it '1:Nとなっている' do
        expect(User.reflect_on_association(:(モデル名)).macro).to eq :has_many
      end
    end
  end
end


統合テスト

showページのテスト


describe 'current_userのitem/showページのテスト' do
  before do
    visit item_path(item) #このページへ遷移した時のテスト
  end

  context '表示内容の確認' do
    it 'URLが正しい' do
      expect(current_path).to eq '/items/' + item.id.to_s
     #URLが'/items/' + item.id.to_sなっているか
    end
    it 'ユーザーの名前のリンク先が正しい' do
      expect(page).to have_link item.user.name, href: user_path(item.user)
     #'item.name'が表示されていてそのリンク先が[user_path(item.user)]
    end
    it 'itemの編集リンクが表示される' do
      expect(page).to have_link 'アイテムを編集', href: edit_item_path(item)
     #'アイテムを編集'表示されていてリンク先が[edit_item_path(item)]
    end
  end
end

editページのテスト

context '編集成功のテスト' do
  before do
    @item_old_genre_id = item.genre_id
    @item_old_name = item.name    
    genre_id = Faker::Number.between(from: 1, to: 6)
    #ジャンルIDが6まで表示する
    select Genre.find(genre_id).name, from: 'item[genre_id]'
    #Genreの中からnameが表示されているものを一つ選択する
    fill_in 'item[name]', with: Faker::Lorem.characters(number: 10)
    #10文字のランダム文字を入れてる
    click_button '更新する'
    #更新するをクリック
  end

  it 'ジャンル名が正しく更新される' do
    expect(item.reload.genre_id).not_to eq @item_old_genre_id
  end
  it 'アイテム名が正しく更新される' do
    expect(item.reload.name).not_to eq @item_old_name
  end
  it 'リダイレクト先が、更新したアイテムの詳細ページになっている' do
    expect(current_path).to eq '/items/' + item.id.to_s
    expect(page).to have_content 'アイテムの詳細'
  end
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