LoginSignup
0
0

More than 3 years have passed since last update.

GitHubからGemを理解する(RSpec編)

Posted at

経緯

プログラミング学習を進める過程で様々なGemを使う。アプリケーションに必要な機能を導入し課題解決を図るツールだが、Gemごとでコーディング規則が異なっており、あやふやに理解しているとツールに溺れかねない。そこでGemの理解を深めることを目指し、GitHub上の元データを覗いてみようと思う。今回はRSpecについて調べてみよう。

方法

今回はGitHub上のrspec-railsのページを参考資料にする。主にトップページを上から順繰りと読み進めていき、気になった箇所についてコメントをしていく。

その1.development環境とtest環境双方で使用できるようにGemを配置する

Add rspec-rails to both the :development and :test groups of your app’s Gemfile:

Gemfile
group :development, :test do
 gem 'rspec-rails', '~> 4.0.1'
end

(Adding it to the :development group is not strictly necessary, but without it, >generators and rake tasks must be preceded by RAILS_ENV=test.)

development環境での設定は強制されていないが、設定をしないと本来development環境でも対応可能なテストまでtest環境で行うことになる。他の開発者と干渉せず、過度な迷惑をかけないdevelopment環境だからこそ、そこで対応できるものは進めようということのようである。

その2.テストの範囲は自身で設定できる

# Default: Run all spec files (i.e., those matching spec/**/*_spec.rb)
$ bundle exec rspec

# Run all spec files in a single directory (recursively)
$ bundle exec rspec spec/models

# Run a single spec file
$ bundle exec rspec spec/controllers/accounts_controller_spec.rb

# Run a single example from a spec file (by line number)
$ bundle exec rspec spec/controllers/accounts_controller_spec.rb:8

テスト範囲をdirectoryやfile、exampleなどで指定できる。全体の流れをテストするのか、特定の箇所だけテストするのか、対象によって無駄のない検証を心がけよう。

その3.テストコードは自然言語とプログラミング言語の双方で記述する

In RSpec, application behavior is described first in (almost) plain English, >then again in test code, like so:

RSpec.describe 'Post' do           #
 context 'before publication' do  # (almost) plain English
   it 'cannot have comments' do   #
     expect { Post.create.comments.create! }.to >raise_error(ActiveRecord::RecordInvalid)  # test code
   end
 end
end

describeに確認する「機能」、contextに確認する「状況」、itに機能もしくは状況についての「具体的内容」を自然言語で記述する。itに記載したものをベースに具体的な確認内容をプログラミング言語として記述する。こうすることで、人もコンピューターも理解できる記述が完成する。

終わりに

GitHub上のデータは情報の宝庫である。コードの意図や本質、TIPS等が記述されておりGemへの内容理解が深まった。原典に当ることの大切さを感じる良い機会であった。他のGemについても同様に実践していきたい。

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