Home > Software design >  How to test this method? (RSpec)
How to test this method? (RSpec)

Time:04-23

def is_doctor
    user = User.find_by(role: 'doctor')
    "Name: #{user.name} | Email: #{user.email}| isActive: #{user.is_active}"  
end

Something like this, but I don't know how to implement it correctly ↓

context 'test' do
  #it { expect(user.is_doctor).to eq("Taras") }
end

CodePudding user response:

I assume doctor? is an instance method on a User model you're using Faker which might help you a lot.

# models/user.rb
class User < ApplicationRecord

  def doctor?
    return 'Not a doc' unless role == 'doctor'

    "Name: #{name} | Email: #{email}| isActive: #{is_active}"
  end
end

# specs/models/user_spec.rb
describe User, type: :model do
  context 'with instance method' do

    describe '#doctor?' do
      subject { user. doctor? }

      context 'with a doctor' do
        let(:user) { create(:user, role: 'doctor') }

        it 'includes name' do
          expect(subject).to include("Name: #{user.name}")
        end
        
        it 'includes email' do
          expect(subject).to include("Email: #{email}")
        end

        it 'includes is_active' do
          expect(subject).to include("isActive: #{is_active}")
        end
      end

      context 'without doctor' do
        let(:user) { create(:user, role: 'foo') }

        it 'has static response' do
          expect(subject).to eq('Not a doc')
        end
      end
    end
  end
end

  • Related