1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【RSpec×Rails×Devise】記事投稿のテストに失敗した理由、解決方法

Posted at

RSpec×Rails×Devise】記事投稿のテストについて

こんにちは。
RSpecで記事投稿機能のテストを行う際に「記事が保存されない…」という壁にぶつかりました。
結論としては「ログインしていなかったから」でした。
備忘録として残します。


問題になったテストコード(初期)

describe 'POST /articles' do
  it '記事が保存される' do
    article_params = attributes_for(:article)
    post articles_path({ article: article_params })
    expect(response).to have_http_status(302)
    expect(Article.last.title).to eq(article_params[:title])
    expect(Article.last.content.body.to_plain_text).to eq(article_params[:content])
  end
end

テスト失敗時のエラー

expected: "scj6wuliim"
     got: "tyomvot9zt"

→ パラメータで送ったタイトルと、実際に保存されたタイトルが一致していない


ログインが必要

多くのアプリでは、記事の投稿はログインユーザーしかできないようになっている。
そのため、RSpecでログイン処理を入れておかないと、記事は保存されずにテストは失敗してしまう。


解決方法:テスト内で sign_in を使用

describe 'POST /articles' do
  context 'ログインしている場合' do
    before do
      sign_in user
    end

    it '記事が保存される' do
      article_params = attributes_for(:article)
      post articles_path({ article: article_params })
      expect(response).to have_http_status(302)
      expect(Article.last.title).to eq(article_params[:title])
      expect(Article.last.content.body.to_plain_text).to eq(article_params[:content])
    end
  end
end

sign_in を使うための設定

RSpec.configure do |config|
  config.include Devise::Test::IntegrationHelpers, type: :request
end

テスト結果

2 examples, 0 failures

わかったこと

  • attributes_for(:article) はただのハッシュ。保存はされない。
  • Article.last を使うと、保存された最新記事の確認ができる。
  • sign_in user でログイン状態を再現しないと、投稿系のテストは通らない!
  • rails_helper.rbrequire 'devise' を忘れると、sign_in が使えない

初学者のため、間違えていたらすいません。
引き続き、学習を進めていきます。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?