LoginSignup
22
18

More than 1 year has passed since last update.

rspecのrequest specでうまくいかない時の原因調査のちょっとしたハック

Last updated at Posted at 2019-12-04

ユースケース

例えば、Rspecのrequest specを以下の様に書いていて、

spec/request/user_spec.rb
it do
  get users_path

  expect(response.code).to eq 200
end

実行したら500で返ってきてちょっと調べても
???ってなった場合のハックです。

$ rspec spec/request/user_spec.rb

Failure/Error: expect(response.code).to eq 200

expected: 200
got: "500"

(compared using ==)

手順

1. リクエストの後にbinding.pryする

spec/request/user_spec.rb
it do
  get users_path

+ bunding.pry
  expect(response.code).to eq 200
end

2. response.bodyを確認

pryコンソールが起動したらresponse.bodyを確認します。
以下の様にHTMLの文字列が返ってくると思います。

$ response.body
=> "<!DOCTYPE html>\n<html>\n<head>\n    <title>NoMethodError at

3. response.bodyをファイル出力

そのままコンソールで以下を実行してhtmlファイルを作成します。

$ File.write("tmp/debug.html", response.body)
$ exit # console抜けます

consoleを抜けて、ファイルが作成されているか確認します。

$ ls -la tmp/
debug.html

4. 作成したファイルをブラウザで表示

このHTMLファイルをブラウザで読み込むとrailsのエラーページが描画されるので多少わかりやすくなります。

$ open tmp/debug.html
22
18
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
22
18