Rspec: undefined method `StandardError' for EmeraldComponent:Module - ruby

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?

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

#victorCui is correct.
Instead of raising StandardError.new(), the recommended approach is to write:
raise StandardError, "message"
See https://github.com/rubocop-hq/ruby-style-guide#exception-class-messages

Related

(RSpec) How do I check if an object is created?

I want to test if expected exception handling is taking place in the following Ruby code through RSpec. Through testing I realized that I cannot use the raise_error matcher to test if the exception was raised, after rescuing it.
So, now I want to test whether objects of CustomError and StandardError are created to see if the error was raised as expected.
test.rb
module TestModule
class Test
class CustomError < StandardError
end
def self.func(arg1, arg2)
raise CustomError, 'Inside CustomError' if arg1 >= 10 && arg2 <= -10
raise StandardError, 'Inside StandardError' if arg1.zero? && arg2.zero?
rescue CustomError => e
puts 'Rescuing CustomError'
puts e.exception
rescue StandardError => e
puts 'Rescuing StandardError'
puts e.exception
ensure
puts "arg1: #{arg1}, arg2: #{arg2}\n"
end
end
end
test_spec.rb
require './test'
module TestModule
describe Test do
describe '#func' do
it 'raises CustomError when arg1 >= 10 and arg2 <= -10' do
described_class.func(11, -11)
expect(described_class::CustomError).to receive(:new)
end
end
end
end
When I run the above code I get the following error
Failures:
1) TestModule::Test#func raises CustomError when arg1 >= 10 and arg2 <= -10
Failure/Error: expect(described_class::CustomError).to receive(:new)
(TestModule::Test::CustomError (class)).new(*(any args))
expected: 1 time with any arguments
received: 0 times with any arguments
# ./test_spec.rb:8:in `block (3 levels) in <module:TestModule>'
The idea was that if CustomError is being raised, it's obejct must be created using new and I can test that using RSpec. However, as you can see, this isn't working.
What am I missing?
Is there a better approach?
What you are trying to do is to test implementation details (what happens inside the method), and usually it's a bad idea. If a particular path leads to an exception but you want this exception to be swallowed - test that.
consider
def weird_division(x, y)
x/y
rescue ZeroDivisionError => e
return "Boom!"
end
No need to test that ZeroDivisionError has been created, that's an implementation detail (akin to testing private methods). Test behavior that is "visible" from the outside.
expect(weird_division(1/0)).to return "Boom!"
Because you might change the implementation:
def weird_division(x, y)
return "Boom!" if y == 0
x/y
end
And your tests would start failing, even though the method behaves the same.
I see two possibilities.
If you want to continue with your assertion you can use have_received instead of receive. This will allow you to keep you assertion after you act.
expect(described_class::CustomError).to have_received(:new)
As mentioned in comments test your puts. Which is ultimately the way that you check if your method does what you want.
it 'puts the output' do
expect do
described_class.func(11, -11)
end.to output('Some string you want to print').to_stdout
end

RSpec hits an error in code, before it is able to expect an error to be raised

This is something that I've seen before when using RSpec Rails and I believe that I know what is happening, I just don't know how I can get around it.
To me, it appears that the following test should pass. It expects an error, and an error is raised although I assume that the source of the error is what it is tripping up on.
csv_file_spec.rb
require 'spec_helper'
RSpec.describe Cleaner::CSVFile do
context 'when CSV file does not exist' do
let(:file) { Cleaner::CSVFile.new('tmp/file-does-not-exist.csv') }
it 'raises error' do
expect(file).to raise_error
end
end
end
csv_file.rb
module Cleaner
# A CSVFile is a CSV file loaded into memory. It exposes the clean method.
class CSVFile
attr_accessor :raw
def initialize(file)
#raw = File.open(file)
end
end
end
Output
1) Cleaner::CSVFile is not valid
Failure/Error: expect(Cleaner::CSVFile.new('tmp/file-does-not-exist.csv')).to raise_error
Errno::ENOENT:
No such file or directory # rb_sysopen - tmp/file-does-not-exist.csv
# ./lib/cleaner/csv_file.rb:8:in `initialize'
# ./lib/cleaner/csv_file.rb:8:in `open'
# ./lib/cleaner/csv_file.rb:8:in `initialize'
# ./spec/csv_file_spec.rb:7:in `new'
# ./spec/csv_file_spec.rb:7:in `block (2 levels) in <top (required)>'
I can see that the CSVFile object is not able to be initialized because the file does not exist and that'll be why RSpesc can't continue the test but what can I do to get around this?
I get the feeling that there is something fundamentally wrong with my approach to testing that I'm not seeing. I'd rather delegate the error to the standard File class, and not raise my own error messages as the error is verbose enough and I'd only be duplicating effort - should I be implementing my own instead?
Thanks!
For exceptions you should use block or lambda in expect syntax:
it 'raises error' do
expect{ Cleaner::CSVFile.new('tmp/file-not-exist.csv') }.to raise_error
end
You could use stubbing also :
require 'spec_helper'
RSpec.describe Cleaner::CSVFile do
context 'when CSV file does not exist' do
it 'raises error' do
allow(described_class).to receive(:new).and_raise("File not exist")
expect { described_class.new }.to raise_error("File not exist")
end
end
end
Read match message with a string.

Rspec: expect vs expect with block - what's the difference?

Just learning rspec syntax and I noticed that this code works:
context "given a bad list of players" do
let(:bad_players) { {} }
it "fails to create given a bad player list" do
expect{ Team.new("Random", bad_players) }.to raise_error
end
end
But this code doesn't:
context "given a bad list of players" do
let(:bad_players) { {} }
it "fails to create given a bad player list" do
expect( Team.new("Random", bad_players) ).to raise_error
end
end
It gives me this error:
Team given a bad list of players fails to create given a bad player list
Failure/Error: expect( Team.new("Random", bad_players) ).to raise_error
Exception:
Exception
# ./lib/team.rb:6:in `initialize'
# ./spec/team_spec.rb:23:in `new'
# ./spec/team_spec.rb:23:in `block (3 levels) in <top (required)>'
My question is:
Why does this happen?
What is the difference between the former and later example exactly in ruby?
I am also looking for rules on when to use one over the other
One more example of the same but inverse results, where this code works:
it "has a list of players" do
expect(Team.new("Random").players).to be_kind_of Array
end
But this code fails
it "has a list of players" do
expect{ Team.new("Random").players }.to be_kind_of Array
end
Error I get in this case is:
Failure/Error: expect{ Team.new("Random").players }.to be_kind_of Array
expected #<Proc:0x007fbbbab29580#/Users/amiterandole/Documents/current/ruby_sandbox/tdd-ruby/spec/team_spec.rb:9> to be a kind of Array
# ./spec/team_spec.rb:9:in `block (2 levels) in <top (required)>'
The class I am testing looks like this:
class Team
attr_reader :name, :players
def initialize(name, players = [])
raise Exception unless players.is_a? Array
#name = name
#players = players
end
end
As has been mentioned:
expect(4).to eq(4)
This is specifically testing the value that you've sent in as the parameter to the method. When you're trying to test for raised errors when you do the same thing:
expect(raise "fail!").to raise_error
Your argument is evaluated immediately and that exception will be thrown and your test will blow up right there.
However, when you use a block (and this is basic ruby), the block contents isn't executed immediately - it's execution is determined by the method you're calling (in this case, the expect method handles when to execute your block):
expect{raise "fail!"}.to raise_error
We can look at an example method that might handle this behavior:
def expect(val=nil)
if block_given?
begin
yield
rescue
puts "Your block raised an error!"
end
else
puts "The value under test is #{val}"
end
end
You can see here that it's the expect method that is manually rescuing your error so that it can test whether or not errors are raised, etc. yield is a ruby method's way of executing whatever block was passed to the method.
In the first case, when you pass a block to expect, the execution of the block doesn't occur until it's time to evaluate the result, at which point the RSpec code can catch any error that are raised and check it against the expectation.
In the second case, the error is raised when the argument to expect is evaluated, so the expect code has no chance to get involved.
As for rules, you pass a block or a Proc if you're trying to test behavior (e.g. raising errors, changing some value). Otherwise, you pass a "conventional" argument, in which case the value of that argument is what is tested.

How to rescue all exceptions under a certain namespace?

Is there a way to rescue all exceptions under a certain namespace?
For example, I want to rescue all of the Errno::* exceptions (Errno::ECONNRESET, Errno::ETIMEDOUT). I can go ahead and list them all out on my exception line, but I was wondering if I can do something like.
begin
# my code
rescue Errno
# handle exception
end
The above idea doesn't seem to work, thus is there something similar that can work?
All the Errno exceptions subclass SystemCallError:
Module Errno is created dynamically to map these operating system errors to Ruby classes, with each error number generating its own subclass of SystemCallError. As the subclass is created in module Errno, its name will start Errno::.
So you could trap SystemCallError and then do a simple name check:
rescue SystemCallError => e
raise e if(e.class.name.start_with?('Errno::'))
# do your thing...
end
Here is another interesting alternative. Can be adapted to what you want.
Pasting most interesting part:
def match_message(regexp)
lambda{ |error| regexp === error.message }
end
begin
raise StandardError, "Error message about a socket."
rescue match_message(/socket/) => error
puts "Error #{error} matches /socket/; ignored."
end
See the original site for ruby 1.8.7 solution.
It turns out lambda not accepted my more recent ruby versions. It seems the option is to use what worked in 1.8.7 but that's IM slower (to create a new class in all comparisons. So I don't recommend using it and have not even tried it:
def exceptions_matching(&block)
Class.new do
def self.===(other)
#block.call(other)
end
end.tap do |c|
c.instance_variable_set(:#block, block)
end
end
begin
raise "FOOBAR: We're all doomed!"
rescue exceptions_matching { |e| e.message =~ /^FOOBAR/ }
puts "rescued!"
end
If somebody knows when ruby removed lambda support in rescue please comment.
All classes under Errno are subclasses of SystemCallError. And all subclasses of SystemCallError are classes under Errno. The 2 sets are identical, so just rescue SystemCallError. This assumes that you're not using an external lib that adds to one and not the other.
Verify the identity of the 2 sets (using active_support):
Errno.constants.map {|name|
Errno.const_get(name)
}.select{|const|
Class === const
}.uniq.map(&:to_s).sort ==
SystemCallError.subclasses.map(&:to_s).sort
This returns true for me.
So, applied to your example:
begin
# my code
rescue SystemCallError
# handle exception
end
Here is a more generic solution, in the case you wanted to rescue some Errno types and not others.
Create a custom module to be included by all the error classes we want to rescue
module MyErrnoModule; end
Customize this array to your liking, up to the "each" call.
Errno.constants.map {|name|
Errno.const_get(name)
}.select{|const|
Class === const
}.uniq.each {|klass|
klass.class_eval {
include MyErrnoModule
}
}
Test:
begin
raise Errno::EPERM
rescue MyErrnoModule
p "rescued #{$!.inspect}"
end
Test result:
"rescued #<Errno::EPERM: Operation not permitted>"
I would guess this performs slightly better than a solution that needs to check the name of the exception.

RSpec test ArgumentError on method with parameters

I'm having problems getting this simple test to pass on RSpec 2.8.
I want to write a simple test for the absence of parameters on a method that requires them (i.e. ArgumentError: wrong number of arguments ('x' for 'y')).
My test is testing a Gem module method like so:
describe "#ip_lookup" do
it "should raise an ArgumentError error if no parameters passed" do
expect(#geolocater.ip_lookup).to raise_error(ArgumentError)
end
end
My gem module code looks like this:
module Geolocater
def ip_lookup(ip_address)
return ip_address
end
end
My spec runs with this output.
Failure/Error: expect(#geolocater.ip_lookup).to raise_error(ArgumentError)
ArgumentError:
wrong number of arguments (0 for 1)
# ./lib/geolocater.rb:4:in `ip_lookup'
# ./spec/geolocater_spec.rb:28:in `block (3 levels) in <top (required)>'
What am I missing here?
You need to pass a block to #expect, not a regular argument:
describe "#ip_lookup" do
it "should raise an ArgumentError error if no parameters passed" do
expect { #geolocater.ip_lookup }.to raise_error(ArgumentError)
end
end

Resources