日曜ITエンジニア劇場

日曜に勉強した情報の整理と、挑戦する新たな技術(私にとって)のつまづきポイントを綴っていきます。

RSpec/マッチャー(matchers)/等価


参考資料

公式サイト

relishapp.com


等価マッチャー使用例

require 'rails_helper'

RSpec.describe '等価matchers' do
  let(:string1) { 'kuro-neko' }
  let(:string2) { string1 }
  let(:integer1) { 3 }
  let(:integer2) { 3.0 }

  describe 'eqを使用' do
    context '内容が同一の文字列の場合' do
      it { expect(string1).to eq(string2) }
    end

    context '内容が異なる文字列の場合' do
      let(:string2) {'shiro-neko'}
      it { expect(string1).not_to eq(string2) }
    end

    context '同一の数値の場合' do
      it { expect(integer1).to eq(integer2) }
    end
  end

  describe '他に...' do
    describe '==を使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to be == string2 }
      end
    end

    describe 'eqlを使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to eql(string2) }
      end
    end

    describe 'equalを使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to equal(string2) }
      end
    end

    describe 'beを使用' do
      context '内容が同一の文字列の場合' do
        it { expect(string1).to be(string2) }
      end
    end
  end
end

実行結果

$ bundle exec rspec spec/sample/matcher_spec.rb

等価matchers
  eqを使用
    内容が同一の文字列の場合
      is expected to eq "kuro-neko"
    内容が異なる文字列の場合
      is expected not to eq "shiro-neko"
    同一の数値の場合
      is expected to eq 3.0
  他に...
    ==を使用
      内容が同一の文字列の場合
        is expected to be == kuro-neko
    eqlを使用
      内容が同一の文字列の場合
        is expected to eql "kuro-neko"
    equalを使用
      内容が同一の文字列の場合
        is expected to equal "kuro-neko"
    beを使用
      内容が同一の文字列の場合
        is expected to equal "kuro-neko"

Finished in 0.0206 seconds (files took 1.26 seconds to load)
7 examples, 0 failures

RSpec/構造


参考資料

1.公式 (rspec-core)

RSpec Core 3.9 - RSpec Core - RSpec - Relish

【引用】上記URLより
rspec-core provides the structure for RSpec code examples
(Google訳)
rspec-coreは、RSpecコード例の構造を提供します。

2.【DSL】改めてDSLを調べてみた

第1回 DSLとは?:今そこにある“DSL”|gihyo.jp … 技術評論社
(↑ 参考になりました🙇🏻‍♀️)

3.【構造】Descrie, context, itについて

rspecのdescribe, context, subject, letなどの書き分け - kei-p3’s blog
(↑ 一番しっくりくる説明でした🙇🏻‍♀️)

4.例の資料(電話番号の最大桁数)

質問!ITmedia - 国内で使われる電話番号の最大桁数は?


describe, context, itの位置付け

下記、参考資料3.を参考に記述。

区分名 位置付け
describe テストグループ class, 属性, method など
context テストケース 「nameがnilの場合」など
it 想定結果 「nameは有効であること」など

コーディングイメージ

※下記は構造のイメージををざっくり掴むための記述であり、飽くまでイメージです。
テストケースは少々、強引な記述をしています。

# 【modelのテストの場合】

# model名
# (↓下記はspecファイルの自動生成時に自動で記述されている)
RSpec.describe User, type: :model do

  # 属性1
  describe 'name' do

    # 検証の種類
    describe '必須チェック' do

      # 検証に対するテストケース(正常系)
      context 'nameにnilまたは空白以外の値がセットされている場合' do

        # 想定結果(正常系)
        it 'nameは有効であること' do
          ...[test_coding]...
        end
      end

      # 検証に対するテストケース(異常系)
      context 'nameにnilがセットされている場合' do

        # 想定結果(異常系)
        it 'nameは無効であること' do
          ...[test_coding]...
        end
      end
    dne
  end

  # 属性2
  describe cell_phone_number do

    # 検証の種類
    describe '桁数チェック' do

      # 検証に対するテストケース(正常系)
      context 'cell_phone_numberに11桁の数値がセットされている場合' do

        # 想定結果(正常系)
        it 'nameは有効であること' do
          ...[test_coding]...
        end
      end


      # 検証に対するテストケース(異常系)
      context 'cell_phone_numberに12桁の数値がセットされている場合' do

        # 想定結果(異常系)
        it 'cell_phone_numberは無効であること' do
          ...[test_coding]...
        end
      end
    end
  end
end

※contextに具体値を記述しない理由
テストデータについて、以前、神と崇めていた人のRSpecのレクチャーで下記の様に言われました。
「意図する区分やコードであれば固定値の使用は構わないが、
それ以外の値は固定値を使用すべきではない。ランダムな値を使用すべき」
この具体例は、後日記載する「テストデータまとめ(Titleは仮)」内のGem「Faker」で記載します。

RSpec/導入、specファイルの生成、実行方法


参考資料

公式サイト

github.com

RSpecの実行ログのフォーマット設定

shinkufencer.hateblo.jp


ありがとうございます! 美しくログが表示されました🙇🏻‍♀️


導入

Gemfileに記述

# 最新の安定版リリースに対して実行する  
group :development, :test do  
  gem 'rspec-rails', '~> 4.0', '>= 4.0.1'  
end  

特定バージョンを指定する場合

下記で記述方法を確認する。他のGemとの依存関係にも注意する。
https://rubygems.org/gems/rspec-rails

ダウンロードとインストール

$ cd [プロジェクトdir]  
$ bundle install  

ボイラープレート構成ファイルを生成する

$ rails generate rspec:install  
  create  .rspec  
  create  spec  
  create  spec/spec_helper.rb  
  create  spec/rails_helper.rb  

メンテナンス/バージョンアップ

$ bundle update rspec-rails  

specファイルの生成

組込ジェネレーターにフックして、specファイルを同時に作成する場合

$ rails generate model user name:string mail:string  
Running via Spring preloader in process 3594  
      invoke  active_record  
      create    db/migrate/20200522093439_create_users.rb  
      create    app/models/user.rb  
      invoke    rspec  
      create      spec/models/user_spec.rb  

RSpec独自のスペックファイルジェネレーターを使用して、specファイルのみ作成する場合

$ rails generate rspec:model color name:string hex_color_code:string  
Running via Spring preloader in process 3871  
      create  spec/models/color_spec.rb  

すべてのRSpecジェネレータの表示方法

$ rails generate --help | grep rspec  
Running via Spring preloader in process 3903  
  rspec:channel  
  rspec:controller  
  rspec:feature  
  rspec:generator  
  rspec:helper  
  rspec:install  
  rspec:integration  
  rspec:job  
  rspec:mailbox  
  rspec:mailer  
  rspec:model  
  rspec:request  
  rspec:scaffold  
  rspec:system  
  rspec:view  

RSpecの実行方法

すべてのテストファイル(*_spec.rb)を実行する

$ bundle exec rspec  

特定ディレクトリ内のテストファイルをすべて実行する

$ bundle exec rspec spec/models  

特定のテストファイルのみを実行する

$ bundle exec rspec spec/models/user_spec.rb  

特定のテストファイルの特定行のみを実行する

$ bundle exec rspec spec/models/user_spec.rb:4  

RSpec実行ログを美しく見せる

.rspecに下記を追記

--format documentation

上記設定後に実行

$ bundle exec rspec spec/sample/matcher_spec.rb

matcher
  等価
    eqの使用
      内容が同一の文字列の比較
        is expected to eq "kuro-neko"
      内容が異なる文字列の比較
        is expected not to eq "shiro-neko"

Finished in 0.05316 seconds (files took 5.55 seconds to load)
2 examples, 0 failures

RSpec実行時に使えるすべてのオプションを表示する

$ bundle exec rspec --help  
Usage: rspec [options] [files or directories]  
  
    -I PATH                            Specify PATH to add to $LOAD_PATH (may be used more than once).  
    -r, --require PATH                 Require a file.  
    -O, --options PATH                 Specify the path to a custom options file.  
        --order TYPE[:SEED]            Run examples by the specified order type.  
                                         [defined] examples and groups are run in the order they are defined  
                                         [rand]    randomize the order of groups and examples  
                                         [random]  alias for rand  
                                         [random:SEED] e.g. --order random:123  
        --seed SEED                    Equivalent of --order rand:SEED.  
        --bisect[=verbose]             Repeatedly runs the suite in order to isolate the failures to the  
                                         smallest reproducible case.  
        --[no-]fail-fast[=COUNT]       Abort the run after a certain number of failures (1 by default).  
        --failure-exit-code CODE       Override the exit code used when there are failing specs.  
    -X, --[no-]drb                     Run examples via DRb.  
        --drb-port PORT                Port to connect to the DRb server.  
  
  **** Output ****  
  
    -f, --format FORMATTER             Choose a formatter.  
                                         [p]rogress (default - dots)  
                                         [d]ocumentation (group and example names)  
                                         [h]tml  
                                         [j]son  
                                         [f]ailures ("file:line:reason", suitable for editors integration)  
                                         custom formatter class name  
    -o, --out FILE                     Write output to a file instead of $stdout. This option applies  
                                         to the previously specified --format, or the default format  
                                         if no format is specified.  
        --deprecation-out FILE         Write deprecation warnings to a file instead of $stderr.  
    -b, --backtrace                    Enable full backtrace.  
        --force-color, --force-colour  Force the output to be in color, even if the output is not a TTY  
        --no-color, --no-colour        Force the output to not be in color, even if the output is a TTY  
    -p, --[no-]profile [COUNT]         Enable profiling of examples and list the slowest examples (default: 10).  
        --dry-run                      Print the formatter output of your suite without  
                                         running any examples or hooks  
    -w, --warnings                     Enable ruby warnings  
  
  **** Filtering/tags ****  
  
    In addition to the following options for selecting specific files, groups, or  
    examples, you can select individual examples by appending the line number(s) to  
    the filename:  
  
      rspec path/to/a_spec.rb:37:87  
  
    You can also pass example ids enclosed in square brackets:  
  
      rspec path/to/a_spec.rb[1:5,1:6] # run the 5th and 6th examples/groups defined in the 1st group  
  
        --only-failures                Filter to just the examples that failed the last time they ran.  
    -n, --next-failure                 Apply `--only-failures` and abort after one failure.  
                                         (Equivalent to `--only-failures --fail-fast --order defined`)  
    -P, --pattern PATTERN              Load files matching pattern (default: "spec/**/*_spec.rb").  
        --exclude-pattern PATTERN      Load files except those matching pattern. Opposite effect of --pattern.  
    -e, --example STRING               Run examples whose full nested names include STRING (may be  
                                         used more than once)  
    -E, --example-matches REGEX        Run examples whose full nested names match REGEX (may be  
                                         used more than once)  
    -t, --tag TAG[:VALUE]              Run examples with the specified tag, or exclude examples  
                                       by adding ~ before the tag.  
                                         - e.g. ~slow  
                                         - TAG is always converted to a symbol  
        --default-path PATH            Set the default path where RSpec looks for examples (can  
                                         be a path to a file or a directory).  
  
  **** Utility ****  
  
        --init                         Initialize your project with RSpec.  
    -v, --version                      Display the version.  
    -h, --help                         You're looking at it.  

MacでSSH接続する

目標

MacからLinux/UbuntuSSH接続する。

参考URL

1.手順について

qiita.com
 ↑
ありがとうございます!助かりました🙇🏻‍♀️

2.SSH接続できない時に確認する項目

ja.stackoverflow.com  ↑
ありがとうございます!おかげさまで解決しました🙇🏻‍♀️

参考書籍

Port番号を変更する理由について

ゼロからはじめるLinuxサーバー構築・運用ガイド 動かしながら学ぶWebサーバーの作り方 [ 中島能和 ]

価格:2,948円
(2020/5/18 23:47時点)

 ↑
CentOSでの解説だが、Linuxの基本的な情報や注意点が分かりやすく
説明されている。
今後も、こちらの書籍を参考にLinuxサーバー構築の練習をしようと思う。

作業環境

$ sw_vers  
ProductName:    Mac OS X  
ProductVersion: 10.15.4  
OS:"Ubuntu"  
VERSION:"14.04.6 LTS, Trusty Tahr"  

実施作業

1.openssh-serverをインストールする。

$ sudo apt-get install openssh-server  

2.sshd_configの編集

$ sudo vi /etc/ssh/sshd_config

# Package generated configuration file  
# See the sshd_config(5) manpage for details  
  
# What ports, IPs and protocols we listen for  
# Port 22  
Port 10022  
...(中略)...  
#PermitRootLogin yes  
PermitRootLogin no  
...(以下、省略)...  
上記の設定について
Port

デフォルトのPort 22は攻撃を受けやすいので変更する。
変更するPort番号は何でもいいが、1024以降で未割付のポート番号を設定する。

PermitRootLogin

rootユーザーでログインすることを
yes:許可する。
no :禁止する。
※参考書籍の解説を参考に記載しています。

3.サーバーの再起動

$ sudo /etc/init.d/ssh restart  
ssh stop/waiting  
ssh start/running, process 3279  

4.Macから接続する。

$ ssh -p 10022 [user_id]@[LinuxマシーンのIPアドレス]  
The authenticity of host '[LinuxマシーンのIPアドレス]:10022 ([192.168.0.5]:10022)' can't be established.  
ECDSA key fingerprint is SHA256:kC5VJXTWAIZC53kItuS0PrPi1fykF2mz2XSqdPVLhCA.  
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes  
Warning: Permanently added '[LinuxマシーンのIPアドレス]:10022' (ECDSA) to the list of known hosts.  
[user_id]@[LinuxマシーンのIPアドレス]'s password:  
Welcome to Ubuntu 14.04.6 LTS (GNU/Linux 3.13.0-170-generic i686)  
  
 * Documentation:  https://help.ubuntu.com/  
  
The programs included with the Ubuntu system are free software;  
the exact distribution terms for each program are described in the  
individual files in /usr/share/doc/*/copyright.  
  
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by  
applicable law.  

【補足】

ssh: connect to host [IPアドレス] port 10022: connection refused  

上記エラーがでたら、下記項目を確認する。
(参考URL2より引用)

IPアドレスが間違っていて、別のPCを指している
・接続先で sshd が起動していない
・接続に使うポートが間違っている
ファイアウォールによって通信が遮断されている