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

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

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.

I chnaged the stubbing like this and it started working
before do
allow(SiteLicenseService).to receive(:get_package_for_site_license).and_return(true)
end
now it does not look for a relation. but i appreciate if anyone tells me what changed internally.

Related

Simplifying `if then` blocks

I have several instances of code that look like this:
if checkProperties(top_properties, payload) == false
return false
end
checkProperties has only one return for false depending on some condition:
def checkProperties(properties, to_check)
properties.each do |property|
if to_check[property.to_s].nil? or to_check[property.to_s].blank?
log_err("Something went wrong")
return false
end
end
end
However I feel this can be simplified. Is it valid to just use the following?
return false unless checkProperties(top_properties, payload)
Any other suggestions?
Don’t return from blocks in the first place. Use break instead:
def checkProperties(properties, to_check)
properties.each_with_object(true) do |property, _|
if to_check[property.to_s].to_s.empty?
log_err("Something went wrong")
break false
end
end
end
or use any? and/or all?:
def checkProperties(properties, to_check)
(!properties.any? { |p| to_check[p.to_s].to_s.empty? }).tap do |good|
log_err("Something went wrong") unless good
end
end
To explicitly show what property was missing, use Enumerable#find:
def empty_property?(properties, to_check)
!!(properties.find { |p| to_check[p.to_s].to_s.empty? }.tap do |prop|
log_err("Property #{prop.inspect} was missing") unless prop.nil?
end)
end
I also took a liberty to renamed a method to follow Ruby naming convention (snake case with a question mark on the end for methods returning true/false.)
Double bang trick is needed to produce true/false out of possible values returned from find: the missing property or nil.
You can check with all? enumerator. This will return true only if all has values below:
def checkProperties(properties, to_check)
properties.all? { |p| to_check[p.to_s] && !to_check[p.to_s].blank? }
end
If any of the property in to_check is nil/absent, all? will return false and stop iterating from there.
Any other suggestions?
A custom error class would work:
class PropertyError < StandardError
end
You could raise it when encountering a missing property:
def check_properties(properties, to_check)
properties.each do |property|
raise PropertyError if to_check[property.to_s].blank?
end
end
This would eliminate the need for conditionals and explicit returns, you'd just have to call:
def foo
check_properties(top_properties, payload)
# do something with top_properties / payload
end
And somewhere "above" you could handle the logging:
begin
foo
rescue PropertyError
log_err 'Something went wrong'
end
Of course, you can also store the missing property's name or other information in the exception to provide a more meaningful error / log message.

My very simple custom Puppet type and provider does not work

I am reading about how to create custom types and providers in Puppet.
But I am getting the error:
Error: Could not autoload puppet/provider/createfile/ruby: undefined method `[]' for nil:NilClass
when running the below code:
mymodule/lib/puppet/type/filecreate.rb
require 'fileutils'
Puppet::Type.newtype(:filecreate) do
ensurable do
defaultvalues
defaultto :present
end
#doc = "Create a file."
newproperty(:name, :namevar => true) do
desc "The name of the file"
end
newproperty(:path) do
desc "The path of the file"
end
end
mymodule/lib/puppet/provider/filecreate/ruby.rb
require 'fileutils'
Puppet::Type.type(:filecreate).provide(:ruby) do
desc "create file.."
puts resource[:name] # this line does not seem to work, why?
puts resource[:path] # this line does not seem to work, why?
def create
puts "create file..."
puts resource[:name]
end
def destroy
puts ("destroy file...")
FileUtils.rm resource[:path]+resource[:name]
end
# Exit method never seems to be called
def exists?
puts "is method beeing called???"
File.exists?(resource[:path])
end
end
I guess the way of fetching the parameter values, puts resource[:name] not is correct. So how can I fetch the filename file.txt declared as the namevar for my custom type filecreate (see below)?
Also, method exists does not seem to be called. Why?
And my init.pp contains this simple code:
class myclass {
filecreate{'file.txt':
ensure => present,
path => '/home/myuser/',
}
}
Your puts calls do not work because you try and access an instance attribute (resource) on the class level. It makes no semantic sense to access the values in this context. Remove those calls.
Generally, it is better to use Puppet.debug instead of puts to collect this kind of information.
To find out where such errors come from, call puppet with the --trace option.

Rspec 3.0 How to mock a method replacing the parameter but with no return value?

I've searched a lot and just cannot figure this out although it seems basic. Here's a way simplified example of what I want to do.
Create a simple method that does something but doesn't return anything, such as:
class Test
def test_method(param)
puts param
end
test_method("hello")
end
But in my rspec test I need to pass a different parameter, such as "goodbye" instead of "hello." I know this has to do with stubs and mocks, and I've looking over the documentation but can't figure it out: https://relishapp.com/rspec/rspec-mocks/v/3-0/docs/method-stubs
If I do:
#test = Test.new
allow(#test).to_receive(:test_method).with("goodbye")
it tells me to stub out a default value but I can't figure out how to do it correctly.
Error message:
received :test_method with unexpected arguments
expected: ("hello")
got: ("goodbye")
Please stub a default value first if message might be received with other args as well.
I am using rspec 3.0, and calling something like
#test.stub(:test_method)
is not allowed.
How to set a default value that is explained at
and_call_original can configure a default response that can be overriden for specific args
require 'calculator'
RSpec.describe "and_call_original" do
it "can be overriden for specific arguments using #with" do
allow(Calculator).to receive(:add).and_call_original
allow(Calculator).to receive(:add).with(2, 3).and_return(-5)
expect(Calculator.add(2, 2)).to eq(4)
expect(Calculator.add(2, 3)).to eq(-5)
end
end
Source where I came to know about that can be found at https://makandracards.com/makandra/30543-rspec-only-stub-a-method-when-a-particular-argument-is-passed
For your example, since you don't need to test the actual result of test_method, only that puts gets called in it passing in param, I would just test by setting up the expectation and running the method:
class Test
def test_method(param)
puts param
end
end
describe Test do
let(:test) { Test.new }
it 'says hello via expectation' do
expect(test).to receive(:puts).with('hello')
test.test_method('hello')
end
it 'says goodbye via expectation' do
expect(test).to receive(:puts).with('goodbye')
test.test_method('goodbye')
end
end
What it seems you're attempting to do is set up a test spy on the method, but then I think you're setting up the method stub one level too high (on test_method itself instead of the call to puts inside test_method). If you put the stub on the call to puts, your tests should pass:
describe Test do
let(:test) { Test.new }
it 'says hello using a test spy' do
allow(test).to receive(:puts).with('hello')
test.test_method('hello')
expect(test).to have_received(:puts).with('hello')
end
it 'says goodbye using a test spy' do
allow(test).to receive(:puts).with('goodbye')
test.test_method('goodbye')
expect(test).to have_received(:puts).with('goodbye')
end
end

Issue stubbing with RSpec

I am trying to understand why the result of these tests, the first test claims the method is not stubbed, however, the 2nd one is.
class Roll
def initialize
install if !installed?
end
def install; puts 'install'; end
end
describe Roll do
before do
class RollTestClass < Roll; end
RollTestClass.any_instance.stub(:install)
end
let(:roll_class) { RollTestClass }
let(:roll) { RollTestClass.new }
context 'when installed is true' do
before do
roll_class.any_instance.stub(:installed?).and_return(true)
end
it 'should not call install' do
expect(roll).to_not have_received(:install)
end
end
context 'when installed is false' do
before do
roll_class.any_instance.stub(:installed?).and_return(false)
end
it 'should call install' do
expect(roll).to have_received(:install)
end
end
end
It's also strange the error says expected to have received install, but I think that is likely just faulty feedback from the RSpec DSL. But maybe worth noting.
1) Roll when installed is true should not call install
Failure/Error: expect(roll).to_not have_received(:install)
#<RollTestClass:0x10f69ef78> expected to have received install, but that method has not been stubbed.
The "spy pattern" of RSpec requires that the objects have been previously stubbed. However, any_instance.stub doesn't actually stub the methods "for real" unless/until the method is invoked on a particular object. As such, the methods appears as being "unstubbed" and you get the error you're getting. Here's some code that demonstrates the change in definition:
class Foo
end
describe "" do
it "" do
Foo.any_instance.stub(:bar)
foo1 = Foo.new
foo2 = Foo.new
print_bars = -> (context) {puts "#{context}, foo1#bar is #{foo1.method(:bar)}, foo2#bar is #{foo2.method(:bar)}"}
print_bars['before call']
foo1.bar
print_bars['after call']
end
end
which produces the following output:
before call, foo1#bar is #<Method: Foo#bar>, foo2#bar is #<Method: Foo#bar>
after call, foo1#bar is #<Method: #<Foo:0x007fc0c3842ef8>.bar>, foo2#bar is #<Method: Foo#bar>
I reported this an issue on RSpec's github site and got this acknowledgement/response.
You can use the following alternative approach, which depends on the recently introduced expect_any_instance_of method.
class Roll
def initialize
install if !installed?
end
def install; puts 'install'; end
end
describe Roll do
before do
class RollTestClass < Roll; end
end
let(:roll_class) { RollTestClass }
let(:roll) { RollTestClass.new }
context 'when installed is true' do
before do
roll_class.any_instance.stub(:installed?).and_return(true)
end
it 'should not call install' do
expect_any_instance_of(roll_class).to_not receive(:install)
roll
end
end
context 'when installed is false' do
before do
roll_class.any_instance.stub(:installed?).and_return(false)
end
it 'should call install' do
expect_any_instance_of(roll_class).to receive(:install)
roll
end
end
end

How can I clear class variables between rspec tests in ruby

I have the following class:
I want to ensure the class url is only set once for all instances.
class DataFactory
##url = nil
def initialize()
begin
if ##url.nil?
Rails.logger.debug "Setting url"
##url = MY_CONFIG["my value"]
end
rescue Exception
raise DataFactoryError, "Error!"
end
end
end
I have two tests:
it "should log a message" do
APP_CONFIG = {"my value" => "test"}
Rails.stub(:logger).and_return(logger_mock)
logger_mock.should_receive(:debug).with "Setting url"
t = DataFactory.new
t = nil
end
it "should throw an exception" do
APP_CONFIG = nil
expect {
DataFactory.new
}.to raise_error(DataFactoryError, /Error!/)
end
The problem is the second test never throws an exception as the ##url class variable is still set from the first test when the second test runs.
Even though I have se the instance to nil at the end of the first test garbage collection has not cleared the memory before the second test runs:
Any ideas would be great!
I did hear you could possibly use Class.new but I am not sure how to go about this.
describe DataFactory
before(:each) { DataFactory.class_variable_set :##url, nil }
...
end
Here is an alternative to the accepted answer, which while wouldn't solve your particular example, I'm hoping it might help a few people with a question in the same vein. If the class in question doesn't specify a default value, and remains undefined until set, this seems to work:
describe DataFactory
before(:each) do
DataFactory.remove_class_variable :##url if DataFactory.class_variable_defined? :##url
end
...
end
Works for me with a class with something more like:
def initialize
##url ||= MY_CONFIG["my value"]
...
end

Resources