Search code examples
ruby-on-railsrspecrspec-rails

How to test a model instance method?


I am having some troubles with implementing a Rspec. I have three models; Post, Tagging, and Tag.

app/models/tag.rb

class Tag < ApplicationRecord
  # associations
  has_many :taggings
  has_many :posts, through: :taggings

  # validations
  validates :name, presence: true, uniqueness: { case_sensitive: false }

  # returns a list of posts that are belonging to tag.
  def posts
      ...
  end
end

I was able to write specs for associations and validations but stuck at writing a spec for the instance method of def posts ... end. Can someone briefly explain how to write this spec? I am new to Rspec so please bear with me.

spec/models/tag_spec.rb

require 'rails_helper'

RSpec.describe Tag, type: :model do
  describe "Associations" do
    it { should have_many(:posts).through(:taggings) }
  end

  describe "Validations" do
    subject { FactoryBot.create(:tag) }

    it { should validate_presence_of(:name) }
    it { should validate_uniqueness_of(:name).case_insensitive }
  end

  describe "#posts" do
    # need help
  end

end

Solution

  • You can do something like:

    describe '#posts' do
      before do
        let(:tag) { Tag.create(some_attribute: 'some_value') }
        let(:tagging) { Tagging.create(tag: tag, some_attribute: 'some_value') }
      end
    
      it "tag should do something" do
        expect(tag.posts).to eq('something')
      end
    
      it "tagging should do something" do
        expect(tagging.something).to eq('something')
      end
    
    end 
    

    That will allow you to test the instance methods on Tag. Basically you want to build the objects that you want to test in a before block and call instance methods on them in the it blocks.