简体   繁体   中英

How do I mock an “unless” method for rails using minitest?

I have some code that I am trying to mock 'myerror' scenario:

class Hello < ApplicationRecord


def first_method
    [{:myid=>1}, {:myid=>2}]
  end

  def second_method
    puts self.first_method
    return nil unless self.first_method
    self.first_method.first
  end

  def third_method
    puts self.second_method.nil? # true
    raise "myerror" unless self.second_method
    puts self.second_method.nil? # true
    self.second_method[:myid]
  end
end

In order to ensure the error happens I need to set "first_method" to nil and in my test (using minitest) I have:

require 'test_helper'

class HelloTest < ActiveSupport::TestCase
  test '#hello_is_normal' do
    h = hellos(:one)
    h.first_method
    h.second_method
    h.third_method
  end



test '#hello_example_should_fail' do
    mock = Minitest::Mock.new
    mock.expect :first_method, nil
    mock.expect :second_method, nil
    mock.expect :nil?, true
    mock.expect :nil?, true

    h = hellos(:one)
    h.stub :second_method, mock do
      puts h.third_method
  end

end end

But It doesn't seem to be working as third_method doesn't result in 'myerror' getting raised.

It appears that your function call of mc.mymethod within the block is returning the mock object which was not given the functionality of the actual mymethod function. That is what this example here would indicate.

I'm not sure if you actually want to stub this method at all. Perhaps just use a let statement to set something to nil then run mc.mymethod on the actual mc.mymethod outside of any stub code block and test that.

That should yield the exception you expect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM