Search code examples
rubyrspectdd

Rspec: undefined method `StandardError' for EmeraldComponent:Module


In my gem I have the following module:

module EmeraldComponent

  def self.create(full_name)
    raise StandardError('Base directory for components is missing.') if base_directory_missing?
    raise StandardError('An Emerald Component must have a name.') if full_name.empty?
    raise StandardError('An Emerald Component must have a namespace.') if simple_name?(full_name)
    write_component(full_name)
    true
  end

  def self.write_component(full_name)
    ## To be implemented
  end

  def self.simple_name?(full_name)
    vet = full_name.split('.')
    vet.length == 1
  end

  def self.base_directory_missing?
    not (File.exist?(EmeraldComponent::BASE_DIRECTORY) && File.directory?(EmeraldComponent::BASE_DIRECTORY))
  end

end

And among my Rspec tests for this module I have these:

context 'create' do

  it 'raises an error if the base directory for components is missing' do
    expect {
      EmeraldComponent.create('test.component.Name')
    }.to raise_error(StandardError)
  end

  it 'raises an error if it receives an empty string as component name' do
    expect {
      EmeraldComponent.create('')
    }.to raise_error(StandardError)
  end

  it 'raises an error if it receives a non-namespaced component name' do
    expect {
      EmeraldComponent.create('test')
    }.to raise_error(StandardError)
  end

  it 'returns true if it receives a non-empty and namespaced component name' do
    expect(EmeraldComponent.create('test.component.Name')).to be true
  end

It happens that when I run the test all of them are passing, except for the first. This gives me the following error.

1) EmeraldComponent Methods create returns true if it receives a non-empty and namespaced component name
Failure/Error: raise StandardError('Base directory for components is missing.') if base_directory_missing?

 NoMethodError:
   undefined method `StandardError' for EmeraldComponent:Module
 # ./lib/EmeraldComponent.rb:10:in `create'
 # ./spec/EmeraldComponent_spec.rb:48:in `block (4 levels) in <top (required)>'

As you may see, it is saying that StandardError is undefined for EmeraldComponent:Module.

But StandardError does not belong to EmeraldComponent:Module!

And besides, this same StandardError is working fine for the other tests!.

I've been fighting this error for a while and then decided to post here. Any suggestions?


Solution

  • You should be doing StandardError.new in place or StandardError in your create method

     def self.create(full_name)
        raise StandardError.new('Base directory for components is missing.') if base_directory_missing?
        raise StandardError.new('An Emerald Component must have a name.') if full_name.empty?
        raise StandardError.new('An Emerald Component must have a namespace.') if simple_name?(full_name)
        write_component(full_name)
        true
      end