LoginSignup
11
10

More than 5 years have passed since last update.

RSpecを単体で使いたい on Docker

Posted at

RailsじゃないRspec3環境を構築する方法 を Docker で構築してみました。
作って、試して、すぐ捨てれるところが Docker の良さでもあり、
参考記事のように RSpec 単体を試す(勉強する)にはもってこいだと思います。
なお、ファイルの内容とディレクトリ構成は、ほぼそのまま流用させてもらっています。(感謝)

環境

  • MacOSX(10.12.6 Sierra)
  • Docker for Mac (インストールしておく)

コードは GitHub に置いてあります。

1. まずはDockerfileの作成

$ vim Dockerfile
Dockerfile
FROM ruby:2.4.1
RUN apt-get update -qq && apt-get install -y build-essential libmysqlclient-dev

RUN mkdir /rspec_sample
WORKDIR /rspec_sample

ADD Gemfile /rspec_sample/Gemfile
ADD Gemfile.lock /rspec_sample/Gemfile.lock

RUN bundle install

2. GemfileとGemfile.lockの作成

$ vim Gemfile
Gemfile
source 'https://rubygems.org'
gem 'rspec'
$ touch Gemfile.lock

3. docker-compose.ymlの作成

$ vim docker-compose.yml
docker-compose.yml
version: '3'
services:
  app:
    build:
      context: .
    command: /bin/bash
    volumes:
      - .:/rspec_sample
    tty: true

補足

  • command:
    • コンテナ起動時にコマンドを irb から /bin/bash に変更
  • tty:
    • コンテナを継続起動させる
    • これがないと起動してもすぐに落ちる

4. Rspecをインストール

$ docker-compose run --rm app bundle exec rspec --init

5. コンテナの起動

$ docker-compose up -d
$ docker ps

       Name            Command    State   Ports
-----------------------------------------------
rspecondocker_app_1   /bin/bash   Up

6. specの作成

$ vim spec/spec_helper.rb
spec_helper.rb
RSpec.configure do |config|
   省略 
  Dir[File.join(File.dirname(__FILE__), "../lib/**/*.rb")].each { |f| require f }
end
$ vim spec/hello_spec.rb
hello_spec.rb
require 'spec_helper'

RSpec.describe Hello do
  it "message return hello" do
    expect(Hello.new.message).to eq "hello"
  end
end

7. Rubyを作成しテスト実行

$ mkdir lib

失敗するケースを作成

$ vim lib/hello.rb
hello.rb
class Hello
  def message
    "helloo"
  end
end

失敗することをテスト

レッドになることを確認

$ docker-compose exec app bundle exec rspec
F

Failures:

  1) Hello message return hello
     Failure/Error: expect(Hello.new.message).to eq "hello"

       expected: "hello"
            got: "helloo"

       (compared using ==)
     # ./spec/hello_spec.rb:5:in `block (2 levels) in <top (required)>'

Finished in 0.06863 seconds (files took 0.14193 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/hello_spec.rb:4 # Hello message return hello

成功するように修正

$ vim lib/hello.rb
hello.rb
class Hello
  def message
    "hello"
  end
end

成功することをテスト

グリーンになることを確認

$ docker-compose exec app bundle exec rspec
.

Finished in 0.00722 seconds (files took 0.14668 seconds to load)
1 example, 0 failures

まとめ

こんな感じで簡単に RSpec を試せる環境が構築できました。
Docker 様様です!

参考サイト

RailsじゃないRspec3環境を構築する方法

11
10
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
11
10