9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RSpecを使用したいいね機能(likes_controller)のテスト

Posted at

はじめに

userが特定のtweetにいいね出来る機能のテスト(likes_controllerのテスト)

factoryにlikes.rbを追加する

spec/factories/likes.rb
FactoryBot.define do
  factory :like do
  end
end

以下はJSONを使用した場合のテストなので、そうでない場合は適時読み解いていただければ

spec/controllers/likes_controller_spec.rb
require 'rails_helper'

RSpec.describe LikesController, type: :controller do
    let(:user) { create(:user) }
    let(:tweet) { create(:tweet) }
    let(:like) { create(:like, user_id: user.id, tweet_id: tweet.id) }

  describe "POST #create" do
    before do
      login_user user
    end


    it "responds with JSON formatted output" do
      post :create, format: :json,
      params: { tweet_id: tweet.id, id: like.id }
      expect(response.content_type).to eq "application/json"
    end

    it "add a new like to the tweet" do
      expect { post :create, format: :json, params: { tweet_id: tweet.id, id: like.id } }.to change{ Like.count }.by(1)
    end
  end

  describe "DELETE #destroy" do
    before do
      login_user user
    end

    it "responds with JSON formatted output" do
      delete :destroy, format: :json,
      params: { tweet_id: tweet.id, user_id: user.id, id: like.id }
      expect(response.content_type).to eq "application/json"
    end

    it "remove a like to the tweet" do
      like = create(:like, user_id: user.id, tweet_id: tweet.id)
      expect { delete :destroy, format: :json, params: { tweet_id: tweet.id, user_id: user.id, id: like.id } }.to change{ Like.count }.by(-1)
    end
  end
end

参考url
RSpec初心者必読!「Everyday Rails - RSpecによるRailsテスト入門」を発売しました

9
9
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
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?