Imnotgood
Imnotgood

Reputation: 3

What a test should test with Rspec in Ruby on Rails application

I'm beginner in Rspec, and actually we asked me to do Rspec test for somes method which are already build but which never have been test (they don't write test before building the method).

And now I'm struggling to know how can I test my method, here is example:

 class ConnectorJob < ActiveJob::Base

  queue_as :connector

  def perform(tenant_id = nil, debug = false)
    tenant_to_sync = Tenant.to_sync(tenant_id)
    return if tenant_to_sync.empty?
    tenant_to_sync.each do |tenant|
      service = MyAPP::ContactToSync.new(tenant, debug).call
      if service.success?
        ConnectorService::Synchronization.new(
          tenant, service.data, debug
        ).call
      end
    end
  end
end

What should I test on this? Should I test the return value is correct or if other method are well called?

Here is what I tried to do

    require "rails_helper"

RSpec.describe ConnectorJob, type: :job do
  it 'is in connector queue' do
    expect(ConnectorJob.new.queue_name).to eq('connector')
  end

  describe 'perform' do
    let (:tenant) { create(:tenant) }
    let (:job) { ConnectorJob.new.perform(tenant.id) }

  context 'with empty tenant' do
      it { expect(ConnectorJob.new.perform(@tenant.id)).to eq nil }
    end

    context 'with tenant' do
      it { expect(ConnectorJob.new.perform(tenant.id)).to eq job }
    end
  end
end

As you can see my last test doesn't have sense but I have no idea what I should write on my Rspec for anticipate the result of this method.

If I check my Rspec coverage, Rspec is telling me I cover 100% of my method but I'm not sure that is correct.

I hope I'm clear, feel free to ask me more details.

Thank you all

Upvotes: 0

Views: 77

Answers (1)

Artem Dorodovskyi
Artem Dorodovskyi

Reputation: 679

I think you should test final result, I mean result after calling ConnectorService::Synchronization.new(...).call and test three cases, e.g. if this call create new user, you should test it:

If tenant_to_sync.empty? == true

 context 'with empty tenant' do
   it { expect(ConnectorJob.new.perform(@tenant.id)).to change(User.count).by(0) }
 end

If service.success? == false

context 'MyAPP::ContactToSync return false' do
   it { expect(ConnectorJob.new.perform(@tenant.id)).to change(User.count).by(0) }
 end

If service.success? == true

context 'success' do
   it { expect(ConnectorJob.new.perform(@tenant.id)).to change(User.count).by(1) }
 end

It should be enough to cover all scenarios.

Upvotes: 1

Related Questions