简体   繁体   中英

Mock method in class using MiniTest

I'm running into an issue mocking a method within a class using Ruby's MiniTest::Mock and stub feature and it's driving me insane. What I am trying to do is set up a way to get an access token by calling a Ruby API which will get the actual access token from a 3rd party site.

This is the class all work will be done in.

class ThisClass
  attr_reader :hauler

  def initialize(hauler)
    @hauler = hauler
  end

  def get_access_token
    access_token = Rails.cache.read("access_token_#{hauler.id}")

    if access_token.blank?
      access_token = ext_access_token
      Rails.cache.write("access_token_#{@hauler.id}", access_token, { expires_in: 3600 })
    end
    
    access_token
  end
  
  def ext_access_token
    # call to external url to get access_token
    # Successful response will be { "data": { "authToken": "new-token"} }"
    url = URI.parse("http://www.fake-login.com/auth/sign_in")
    res = Net::HTTP.post_form(url, "userName" => @hauler[:client_id], "password" => @hauler[:client_secret])
    json_response = JSON.parse(res.body)
    json_response["data"]["authToken"]
  end

end

The test is as follows

class ThisClassTest < ActiveSupport::TestCase
  test "Get Access Token" do
    hauler = haulers(:one)
    tc = ThisClass.new(hauler)
    mock_client = MiniTest::Mock.new
    mock_client.expect :ext_access_token, "\"{ \"data\": { \"authToken\": \"new-token\"} }\""

    ThisClass.stub(:ext_access_token, mock_client) do
      puts tc.get_access_token
    end 
    assert_equal true, true
  end
end

When I run my tests, I get the following error

Error:
ThisClassTest#test_Get_Access_Token:
NameError: undefined method `ext_access_token' for class `ThisClass'

I'm clearly doing something wrong since all I want is for the ext_access_token method to return the same data string so I can run logic against it, but very much failing. ThisClass is fairly simplistic but outlines the setup I'll be going with moving forward for more complex methods based on the return from the external site.

The test can't find ext_access_token method because it's looking for a class method on the ThisClass , rather than an instance method.

So what you need is something like

    tc.stub :ext_access_token, mock_client do
      puts tc.get_access_token
    end 

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