New-Village

月間ブログ。だいたい1カ月に1回は更新しているようです。

Nitrousでアプリ作成(認証テスト編)

先にインストールしたdeviseのテストを作成してみました。

なお、固定ページのリンクは"Log in/out"としていましたが、deviseのボタンは"Sign in/out"なので、"Sign in/out"で統一しました。

 

とりあえずビール

まずはブランチを作ります。すぐに環境を壊すおっちょこちょいには必須です。

~/workspace/appname(master)$ git checkout -b "login" 

テストの作成

ファクトリーの設定

順序が逆になってしまったが、認証に関する基本的なテストを作成。

まずは、ユーザテストを楽にする為にテスト環境に"Factory Girl"をインストールします。./gemfileを以下のように編集します。

group :test do

 ...
 gem 'factory_girl_rails', '~>4.2'
end

上記の通り編集したら、コマンドラインからインストールを実施します。 

$ bundle install

ファクトリーのインストールが終わったら、./spec/factories.rbを作成して、ログインするユーザを以下のように設定します。

FactoryGirl.define do
 factory :user do
  email "myapps@example.com"
  password "password"
  password_confirmation "password"
 end
end

サインインのテストを作成

まずはトップ画面にサインイン用のリンクが作成されていることを確認するために、./spec/requests/static_pages_spec.rbに、"Sign In"のリンクを確認するテストを追加します。

describe "Static pages" do

 subject { page }

  describe "Home page" do
   before { visit root_path }

   ...

   it { should have_link('Sign in', href: new_user_session_path) }
  end

  ...

end

次にdeviseで作成されたユーザモデルをテストするために、spec/models/user_spec.rbを以下のように作成します。

describe User do

 before { @user = User.new(email: "user@example.com", encrypted_password: "password") }

 subject { @user }

 it { should respond_to(:email) }

 it { should respond_to(:encrypted_password) }

end

そして、spec/requests/user_pages_spec.rbを作成して、ログイン画面のテストを行います。ファイルを作成したら以下のように設定します。

require 'spec_helper'

describe "ユーザー画面" do

 subject { page }

 describe "ログインテスト" do
  before { visit new_user_session_path }

  describe "誤ったログイン" do
   before { click_button "Sign in" }

   it { should have_title('Sign in') }
   it { should have_selector('p.alert.alert-error', text: 'Invalid email or password') }
  end

  describe "正しいログイン" do
   let(:user) { FactoryGirl.create(:user) }
   before do
    fill_in "Email", with: user.email.upcase
    fill_in "Password", with: user.password
    click_button "Sign in"
   end

   it { should have_selector('p.alert.alert-notice', text: 'Signed in successfully') }
   it { should have_link('Profile', edit_user_registration_path) }
   it { should have_link('Sign out', href: destroy_user_session_path) }
   it { should_not have_link('Sign in', href: new_user_session_path) }
  end

 end
end

 ここまで設定が終わったら、テストを実行。

~/workspace/appname(login*)$ rspec spec

 

エラー:テストできない

rspecを実行したら以下のエラーが出た。

/home/action/.rvm/gems/ruby-2.1.1@railstutorial_rails_4_0/gems/activerecord-4.0.4/lib/active_record/migration.rb:383:in `check_pending!': Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=test' to resolve this issue. (ActiveRecord::PendingMigrationError)  

Stackoverflowで確認すると、テスト環境のDBを作っていないとの事。 なるほど、作ってない。ということで、以下のコマンドを実行したらエラーが解消された。

~/workspace/appname(login*)$ rake test:prepare