mardi 19 septembre 2017

How to test adding friends (User model CREATE Friendship) in RSpec?

I was watching Railscasts on how to add friends here. I built a User and Friendship model. User can add other Friends.

Models:

  #user.rb
  has_many :friendships
  has_many :friends, through: :friendships

  #friendship.rb
  belongs_to :user
  belongs_to :friend, class_name: "User"

DB

  #schema
    create_table "friendships", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "friend_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", force: :cascade do |t|
    t.string   "name"
   ...

Controller:

  #friendships_controller

class FriendshipsController < ApplicationController
  def create
    @friendship = current_user.friendships.build(friend_id: params[:friend_id])
    if @friendship.save
      flash[:notice] = "New friend added!"
      redirect_to root_url
    else
      flash[:error] = "Error adding friend"
      redirect_to root_url
    end
  end
end

To summarize, User can add other user as friend by creating a new Friendship object. This Friendship object contains user_id (the adder) and friend_id (the added). I am trying to figure out how to test this on RSpec.

I tried (and various combinations)

  describe "POST #Create" do
    it "adds new friend" do
      expect {
        post :create
      }.to change(Friendship, :count).by(1)
    end
  end

But it didn't work. I am fairly new at RSpec. How can I test User adding other Friend?

Aucun commentaire:

Enregistrer un commentaire