LoginSignup
15

More than 5 years have passed since last update.

環境変数を利用するRails4プロジェクトでGuardによる自動テスト環境を作る

Posted at

Rails 4.0.2でプロジェクトを進めているのですが、Spring + Guardでテスト環境を作ろうとしたところちょっと手間取ったのでそのメモを。先に利用したgemのバージョン番号を明記しておきます。

guard-rspec (4.2.4)
spring (1.0.0)
spring-commands-rspec (1.0.1)
dotenv-rails (0.9.0)

初期状態&Guardのインストール

まず作業開始前の状況を。rspecは以下のように環境変数を読み込んで動作してました。具体的にはAWS関連の情報をconfig.shに入れてあります。

$ source ~/path/to/this_project_env.sh
$ RAILS_ENV=test bundle exec rspec

この状態からまずguardのセットアップを行いました。

$ bundle exec guard init

spring-commands-rspec の導入

ここでGuardのREADMEに書かれているように生成されたGuardfileにオプションを引き渡しました。

guard :rspec, cmd: 'spring rspec' do

しかし、これで実行するとなぜか以下のようなエラーが

Version: 1.0.0

Usage: spring COMMAND [ARGS]

Commands for spring itself:

  binstub         Generate spring based binstubs. Use --all to generate a binstub for all known commands.
  help            Print available commands.
  status          Show current status.
  stop            Stop all spring processes for this project.

Commands for your application:

  rails           Run a rails command. The following sub commands will use spring: console, runner, generate, destroy.
  rake            Runs the rake command

どうもspringが受け付けるコマンドにrspecが登録されていないようです。bundle exec spring とすると上記のエラーが再度表示されます。そこで、いろいろ調べてspring-commands-rspecを導入。すると、今度はbundle exec spring実行時にサポートされるコマンドにrspecがリストアップされました。

Version: 1.0.0

Usage: spring COMMAND [ARGS]

Commands for spring itself:

(中略)

Commands for your application:

  rails           Run a rails command. The following sub commands will use spring: console, runner, generate, destroy.
  rake            Runs the rake command
  rspec           Runs the rspec command

これでGuardがrspecをspring経由で走らせてくれるようになりました。なお、springで動作しているかどうかは、一度springを停止した上でそれをstatusコマンドで確認し、guard実行後に再度statusを見てspringが立ち上がっているかどうかでわかります。

spring stop
spring status

dotenv gem

さて、これでテストは全部走るのですが、環境変数の読み込みが行われていないのでエラーが発生します。環境変数はbundle exec guardで引き継がれないので、guard実行時に読み込むようにする必要があります。Googleで調べるとdotenvというgemが見つかりました。これはプロジェクトルートに.envというファイルを設置すると、そこからRails実行時に環境変数を読み込んでくれるものです。このgemをGemfileに記載してbundle installし、.envファイルに環境変数を記述すると上述したコマンドライン経由でのrspecと同様の実行結果となりました。

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
15