rubyrspecruby-on-rails-5rspec-railsrspec3

stubbing a class method inside a method in rspec to return true


here is the class for which i'm writing a rspecs.

# frozen_string_literal: true. Thiis is the method **SiteLicenseService.get_package_for_site_license site_license_id, package_id**

module SiteLicenseGrants
  # Raise an error if no site license is found for a given package
  class Package
    # Fail if the given packages are not found or if they are not associated
    # with the site license
    def self.valid_package?(opts)
      package_id = opts[:package_id]
      site_license_id = opts[:site_license_id]
      return true if SiteLicenseService.get_package_for_site_license site_license_id, package_id
    rescue Errors::EntityNotFound
      raise Errors::NoSiteLicenseForPackage.new package_id # rubocop:disable Style/RaiseArgs
    end
  end
end

i want to stub a class method to return true.

require "rails_helper"

RSpec.describe SiteLicenseGrants::Package do
  describe "check valid package" do

    context "valid package" do
      let(:package_id) { 1 }
      let(:site_license_id) { 1 }
      let(:opts) { { package_id: package_id, site_license_id: site_license_id } }
      before do
        site_license_service = class_double("SiteLicenseService")
        allow(site_license_service).to receive(:get_package_for_site_license).with(site_license_id, package_id).and_return(true)
      end

      it "returns true" do
        expect do
          described_class.valid_package?(opts)
        end.to be_truthy
      end
    end

    context "invalid package" do
      let(:opts) { { package_id: nil, site_license_id: nil } }
      it "throws error" do
        expect do
          described_class.valid_package?(opts)
        end.to raise_error(Errors::NoSiteLicenseForPackage)
      end
    end
  end
end

here is the error im getting

Failures:

  1) SiteLicenseGrants::Package check valid package valid package returns true
     Failure/Error: raise Errors::NoSiteLicenseForPackage.new package_id # rubocop:disable Style/RaiseArgs
     
     Errors::NoSiteLicenseForPackage:
       Package 1 doesn't have a site license associated with it

I just want to mock my class method to return true. I dont want to test the class methods of SiteLicenseService. I dont want to create site license with package literally.

can anyone explain me what is the mistake i'm doing.

Thanks


Solution

  • Ensure the syntaxing of mocking the return value is correct:

     allow(SiteLicenseService).to 
     receive(:get_package_for_site_license).and_return(true)
    

    In Ruby, classes are written in TitleCase and methods are written in snake_case. The method to be received should be a :symbol.