Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stub a method to raise an error using Ruby MiniTest?

Tags:

I'm trying to test a Rails controller branch that is triggered when the model method raises an error.

def my_controller_method   @my_object = MyObject.find(params[:id])    begin     result = @my_object.my_model_method(params)   rescue Exceptions::CustomError => e     flash.now[:error] = e.message            redirect_to my_object_path(@my_object) and return   end    # ... rest irrelevant end 

How can I get a Minitest stub to raise this Error?

it 'should show redirect on custom error' do   my_object = FactoryGirl.create(:my_object)    # stub my_model_method to raise Exceptions::CustomError here    post :my_controller_method, :id => my_object.to_param   assert_response :redirect   assert_redirected_to my_object_path(my_object)   flash[:error].wont_be_nil end 
like image 618
s01ipsist Avatar asked Jun 12 '12 04:06

s01ipsist


People also ask

What is mocking in Ruby on Rails?

You use mocks to test the interaction between two objects. Instead of testing the output value, like in a regular expectation. For example: You're writing an API that flips images. Instead of writing your own image-manipulation code you use a gem like mini_magick .

What is Ruby Minitest?

What is Minitest? Minitest is a testing tool for Ruby that provides a complete suite of testing facilities. It also supports behaviour-driven development, mocking and benchmarking. With the release of Ruby 1.9, it was added to Ruby's standard library, which increased its popularity.

Does rails Minitest?

Minitest is the default testing suite used with Rails, so no further setup is required to get it to work.


2 Answers

require "minitest/autorun"  class MyModel   def my_method; end end  class TestRaiseException < MiniTest::Unit::TestCase   def test_raise_exception     model = MyModel.new     raises_exception = -> { raise ArgumentError.new }     model.stub :my_method, raises_exception do       assert_raises(ArgumentError) { model.my_method }     end   end end 
like image 151
Panic Avatar answered Jan 08 '23 01:01

Panic


One way to do this is to use Mocha, which Rails loads by default.

it 'should show redirect on custom error' do   my_object = FactoryGirl.create(:my_object)    # stub my_model_method to raise Exceptions::CustomError here   MyObject.any_instance.expects(:my_model_method).raises(Exceptions::CustomError)    post :my_controller_method, :id => my_object.to_param   assert_response :redirect   assert_redirected_to my_object_path(my_object)   flash[:error].wont_be_nil end 
like image 32
blowmage Avatar answered Jan 08 '23 03:01

blowmage