BriceB BriceB - 8 months ago 67
Ruby Question

Rspec on lib + initializer

I'm trying to test a lib I've created. It auto load with an initializer.

Here is what I have

# config/initializer/my_lib.rb
MyLib.configure do |config|
config.salt = Rails.application.secrets.encrypted_salt
config.secret = Rails.application.secrets.encrypted_secret
end

# lib/my_lib.rb
class MyLib

class << self
attr_accessor :configuration

def config
@configuration ||= Configuration.new
end

def configure
yield(config)
raise 'Salt not specified' unless config.salt
raise 'Secret not specified' unless config.secret
end
end

class Configuration
attr_accessor :salt, :secret
end
end


What I would like is to test that without
salt
and
secret
,
MyLib.configure
will raise an
RuntimeError
.

I've tried the following test but I'm stuck with the block I think

allow(described_class).to receive(:configure) do |&config|
config.salt = nil
config.secret = nil
end


In the previous example both
|config|
and
|&config|
give me a
nil
value for
config
.

max max
Answer Source

Use expect error:

expect do
  MyLib.configure do |config|
    config.salt   = nil
    config.secret = nil
  end
end.to raise_error RuntimeError 

But I would recommend that you create your own exception class such as MyLib::ConfigurationError as RuntimeError could have other causes and the test could actually pass if there is a bug in the code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download