Rails unit testing - ruby-on-rails

In one of my Rails test case:
test "something" do
assert_raise RuntimeError do
#foo.bar
end
end
I set up the #foo object such that #foo.bar does not raise RuntimeError (ie, the test case will fail)
But the following code passed the test:
test "something" do
blah(#foo)
end
private
def blah(foo)
assert RuntimeError do
foo.bar
end
end
Why is this so?

- assert RuntimeError do
+ assert_raise RuntimeError do

Related

MiniTest::Assertion: StandardError expected but nothing was raised

I am using minitest for tests for my ruby on rails. I have a problem in it, what I was try to do was stubbing a method to return exception. And check if exception raises.
class MyProject
def operations
begin
perform_addtion
rescue StandardError => e
puts e
end
end
def perform_addition
*/ some code */
end
end
I was trying to manually raise exception from perform_addition method like this
def test_my_project
MyProject.any_instance.expects(:perform_addition).raises(StandardError)
assert_raises StandardError do
MyProject.new.operations
end
end
The thing is I can see the stubbed exception is raised and control goes to the rescue block in operations method when I checked with debugger but assert_raises fails and throws StandardError expected but nothing was raised
Can someone tell why its like this. Then how can I check if the rescue is executed
Here's a probably proper solution for this case. I think it's self-explanatory, but feel free to ask questions of any kind
The app:
class MyProject
# you can omit begin, and in methods, you can just write rescue
def operations
perform_addtion
rescue StandardError => e
puts e
# Your rescue "ate" your exception, so you need to raise it again
raise e
end
# add a raise to test
def perform_addition
raise StandardError
end
end
The test:
require 'minitest/autorun'
require 'minitest/mock'
require_relative 'my_project'
class MyProjectTest < Minitest::Test
def test_operations
# create mock for MyProject
mock_my_project = Minitest::Mock.new
# create stub for MyProject
def mock_my_project.operations
raise StandardError
end
# use stub in test
MyProject.new.stub :operations, mock_my_project do
assert_raises StandardError do
MyProject.new.operations
end
end
end
end

raise_error spec not returning true in Rspec 3.4

I have the following class, that I am trying to write a spec for:
module IntegrationError
class Error < StandardError; end
class BadRequest < IntegrationError::Error; end
class LogicProblem < IntegrationError::Error; end
def raise_logic_error!(message)
raise IntegrationError::LogicProblem, message
rescue => e
Rails.logger.error e.message
e.backtrace.each do |line|
Rails.logger.error line if line.include?('integrations')
end
end
def raise_bad_request!(message)
raise IntegrationError::BadRequest, message
end
def log_bad_request!(message)
Rails.logger.info message
end
end
with spec
RSpec.describe 'IntegrationError', type: :integration do
let!(:klass) { Class.new { include IntegrationError } }
describe '#log_bad_request!' do
it 'logs it' do
expect(klass.new.log_bad_request!('TESTME')).to be_truthy
end
end
describe '#raise_bad_request!' do
it 'raises it' do
binding.pry
expect(klass.new.raise_bad_request!('TESTME')).to raise_error
end
end
end
the raise_bad_request test returns the error instead of true. Anyone have thoughts on how to write this better to it passes?
I'm using Rails 4 and Rspec 3.4.
If I recall correctly, I believe you need to pass the expectation a block when your raising, like this:
describe '#raise_bad_request!' do
it 'raises it' do
binding.pry
expect{klass.new.raise_bad_request!('TESTME')}.to raise_error
end
end
See docs here
For the raise_error matcher you need to pass a block to expect instead of a value:
expect { klass.raise_bad_request!('TESTME') }.to raise_error
That should do it!

rspec: how to test the ensure block after raised an error

Here's my begin..rescue..ensure block. I want to write some test cases that after error is raised, the final result {} will be returned.
I am using rspec 3.3.
def external_call
result = ExternalApi.call
rescue => e
# handle the error, and re-raise
Handler.handle(e)
raise
ensure
result.presence || {}
end
I have wrote test case for the rescue part:
context 'when external api raise error' do
it 'handles the error, and re-raise' do
allow(ExternalApi).to receive(:call).and_raise(SomeError)
expect(Handler).to receive(:handle).with(e)
expect { subject.external_call }.to raise_error(SomeError)
end
end
But I am not sure how to test the ensure part after the error is re-raised.
Here's my attempt:
it 'returns {} after error raised' do
allow(ExternalApi).to receive(:call).and_raise(SomeError)
result = subject.external_call
expect(result).to eq({})
end
In this case, the test case will fail in the subject.external_call line, since it will raise error there. I am not sure how to test this cases after the error is re-raised.
When using begin/rescue/ensure block with implicit returns, ruby will return the last method to be run in the rescue block as the return value, not the ensure. If the value from the ensure block needs to be returned, it will either have to be explicitly returned, or not included in an ensure but instead moved outside of the begin/rescue block.
Below is an example which shows the difference.
class TestClass
def self.method1
raise 'an error'
rescue
'rescue block'
ensure
'ensure block'
end
def self.method2
raise 'an error'
rescue
'rescue block'
ensure
return 'ensure block'
end
def self.method3
begin
raise 'an error'
rescue
'rescue block'
end
'ensure equivalent block'
end
end
RSpec.describe TestClass do
it do
# does not work, method1 returns 'rescue block'
expect(TestClass.method1).to eql 'ensure block'
end
it do
# does work, as method2 explicitly returns 'ensure block'
expect(TestClass.method2).to eql 'ensure block'
end
it do
# does work, as method3 uses 'ensure equivalent block' as the inferred return
expect(TestClass.method3).to eql 'ensure equivalent block'
end
end

How do I test the rescue block of a method with rspec mocks 3.3

Help me make this test pass:
Here is an example of some rspec code,
class User
attr_accessor :count
def initialize
#count = 0
end
# sometimes raises
def danger
puts "IO can be dangerous..."
rescue IOError => e
#count += 1
end
#always raises
def danger!
raise IOError.new
rescue IOError => e
#count += 1
end
end
describe User do
describe "#danger!" do
it "its rescue block always increases the counter by one" do
allow(subject).to receive(:'danger!')
expect {
subject.danger!
}.to change(subject, :count).by(1)
end
end
describe "#danger" do
context "when it rescues an exception" do
it "should increase the counter" do
allow(subject).to receive(:danger).and_raise(IOError)
expect {
subject.danger
}.to change(subject, :count).by(1)
end
end
end
end
I've also created a fiddle with these tests in it, so you can just make them pass. Please help me test the rescue block of a method!
Background:
My original question went something like this:
I have a method, like the following:
def publish!(resource)
published_resource = resource.publish!(current_project)
resource.update(published: true)
if resource.has_comments?
content = render_to_string partial: "#{ resource.class.name.tableize }/comment", locals: { comment: resource.comment_content_attributes }
resource.publish_comments!(current_project, published_resource.id, content)
end
true
rescue Bcx::ResponseError => e
resource.errors.add(:base, e.errors)
raise e
end
And I want to test that resource.errors.add(:base, e.errors) is, in fact, adding an error to the resource. More generally, I want to test the rescue block in a method.
So I'd like to write code like,
it "collects errors" do
expect{
subject.publish!(training_event.basecamp_calendar_event)
}.to change(training_event.errors.messages, :count).by(1)
end
Of course, this raises an error because I am re-raising in the rescue block.
I've seen a few answers that use the old something.stub(:method_name).and_raise(SomeException), but rspec complains that this syntax is deprecated. I would like to use Rspec Mocks 3.3 and the allow syntax, but I'm having a hard time.
allow(something).to receive(:method_name).and_raise(SomeException)
would be the new allow syntax. Check out the docs for reference.
I was misunderstanding what the allow syntax is actually for. So to make my example specs pass, I needed to do this:
describe "#danger" do
context "when it rescues an exception" do
it "should increase the counter" do
allow($stdout).to receive(:puts).and_raise(IOError) # <----- here
expect {
subject.danger
}.to change(subject, :count).by(1)
end
end
end
This thing that I'm stubing is not the method, or the subject, but the object that might raise. In this case I stub $stdout so that puts will raise.
Here is another fiddle in which the specs are passing.

How to test a super classes method throws an exception using rspec with Ruby

I am trying to find the best way of writing an rspec test that will spec the call to
mail(mail_content).deliver
and raise an exception so I can assert the Rails.logger is called.
I know you are not meant to mock the class under test but does this apply to super classes?
class MyMailer < ActionMailer::Base
default from: 'test#test.com'
default charset: 'UTF-8'
default content_type: 'text/plain'
default subject: 'Test'
def send_email (to, mail_headers_hash, mail_body)
begin
headers mail_headers_hash
mail_content = {to: to, body: mail_body}
mail(mail_content).deliver
rescue ArgumentError, StandardError => e
Rails.logger.error "Failed to email order response - #{e}"
end
end
end
end
With RSpec you could stub raising exception. See the following code snippet:
whatever.should_receive(:do_some_stuff).and_raise(ArgumentError)

Resources