高木のブログ

SinatraアプリにRSpecを導入する

· 168 words · 1 minutes to read
Tags: Ruby Sinatra

おうちハックで使っているSinatraで作ったちょっとしたAPIにRSpecを導入した
SinatraにRSpecを導入する記事がそんなに多くなく、どのやり方が正解かわからなかった
もちろん正解なんて存在しないけど、自分なりの最小限の導入方法がわかったので記録しておく

サンプルとして、「Hello World!」を返すAPIを用意した
このAPIのテストを書いていく

require 'sinatra'

get '/' do
  "Hello World!\n"
end
$ curl localhost:4567
Hello World!

手順 🔗

Gemを追加 🔗

test グループに rspec と rack-test のGemを追記する

group :test do
  gem 'rspec'
  gem 'rack-test'
end

bundle install を忘れない

RSpecの初期化 🔗

$ bundle exec rspec --init
  create   .rspec
  create   spec/spec_helper.rb

.rspec と spec/spec_helper.rb が生成される

RSpecの設定 🔗

生成された spec/spec_helper.rb に追記する

+ENV['APP_ENV'] = 'test'

+require 'sinatra'
+require 'rspec'
+require 'rack/test'

 RSpec.configure do |config|
   config.expect_with :rspec do |expectations|
     expectations.include_chain_clauses_in_custom_matcher_descriptions = true
   end

   config.mock_with :rspec do |mocks|
     mocks.verify_partial_doubles = true
   end

   config.shared_context_metadata_behavior = :apply_to_host_groups

+  config.include Rack::Test::Methods

+  def app
+    Sinatra::Application
+  end
 end

テストを追加 🔗

require './app'

RSpec.describe 'app' do
  it 'says Hello World!' do
    get '/'
    expect(last_response.status).to eq 200
    expect(last_response.body).to eq "Hello World!\n"
  end
end
  • ステータスコードが 200 になっているか
  • レスポンスボティが Hello World!\n になっているか を確認するテストを書いた

テストを実行 🔗

$ bundle exec rspec
.

Finished in 0.02466 seconds (files took 0.72422 seconds to load)
1 example, 0 failures

良きね

参考 🔗

Categories


Tags