yujiro's blog

エンジニアリング全般の事書きます

Rspec 導入と簡単な使い方【Rails】

導入

Rails 5.0.6 に導入しています。

Gemfile に

gem "rspec-rails", "~> 3.1.0"

を追加。

$ bundle install

$ bin/rails g rspec:install

これで spec ディレクトリとか rails_helper, spec_helper ができる。

rails_helper と spec_helper の違いは下記のとおり

rspec-rails のREADMEを読むと、これからは spec/rails_helper.rb に Rails 特有の設定を書き、spec/spec_helper.rbには RSpec の全体的な設定を書く、というようにお作法が変わるそうです。これによって、Railsを必要としないテストを書きやすくなるんだとか。

RSpec 3 時代の設定ファイル rails_helper.rb について - おもしろwebサービス開発日記

なにかテストを実行してみると

テスト環境のDBに対してマイグレーションをしろ、とでるので、

export RAILS_ENV=test; bin/rails db:migrate

とする。 そうすると

undefined method `last_comment' for #<Rake::Application:0x007f2f999691d0>

となる。

これを解消するためにGemfile に以下を追加。

gem 'rake', '< 11.0'  

それで

$ bundle update rake

これで準備完了

使い方

なにか簡単にテストコードを書いて実行してみようと思う。

テストの用途は色々あると思うんだけど、例えば外部サイトをスクレイピングしているようなサービスを運営している場合、 外部サイトの構造が変わったりしたら情報が取れなくなる。 なので1日1回とか定期的にテストを実行させて、取得できなくなってたら通知とかしてると便利ですよね。

今回はwikipedia のTOPページから「今日の一枚」ってところの画像のURLをとってくるロジックのテストコードを書いてみようと思う。

テスト対象コード

app/services/sites/wikipedia.rb
module Services

  module Sites

    module Wikipedia

      def self.get_today_image(url)
        agent = Mechanize.new
        page = agent.get(url)
        image_url = page.search('#mp-right').first.search('.image').first.search('img').first[:src]
        image_url.gsub('//','https://')
      end

    end

  end

end

テストコード

spec/services/sites/wikipedia_spec.rb
require 'rails_helper'

describe 'Wikipedia' do

  it "return the today image url" do
    agent = Mechanize.new
    url = 'https://ja.wikipedia.org'
    page = agent.get(url)
    while page.code[/30[12]/]
      url = page.header['location']
    end
    result = Services::Sites::Wikipedia::get_today_image(url)
    expect(result.include?('.jpg')).to be true
  end

end

Mechanize つかってますが、普通に Gemfile に

gem 'mechanize'

かいてbundle install でOKです。

    url = 'https://ja.wikipedia.org'
    page = agent.get(url)
    while page.code[/30[12]/]
      url = page.header['location']
    end

ここの部分はリダイレクト先のURLを取得してるだけです。

https://ja.wikipedia.org/wiki/メインページ

です。

テストの実行は

bin/rspec spec/services/sites/wikipedia_spec.rb

でOKです。

.

Finished in 2.26 seconds (files took 2.13 seconds to load)
1 example, 0 failures

こんなメッセージが返ってきたら成功です。

これをJenkins とかに登録して、失敗したらSlackに通知とかすればいいんじゃないかな。