1

I am having a method which returns the price of a given symbol and i am writing a test for that method.

This is my test

 def setup
   @asset = NetAssetValue.new
 end

 def test_retrieve_price_for_symbol_YHOO
   assert_equal(33.987, @asset.retrieve_price_for_a_symbol('YHOO'))
 end

 def test_retrive_price_for_YHOO        
   def self.retrieve_price_for_a_symbol(symbol)
     33.77
   end

   assert_equal(33.97, @asset.retrieve_price_for_a_symbol('YHOO'))
 end

This is my method.

def retrieve_price_for_a_symbol(symbol)
  symbol_price = { "YHOO" => 33.987, "UPS" => 35.345, "T" => 80.90 }
  raise Exception if(symbol_price[symbol].nil?)
  symbol_price[symbol]
end

I am trying to mock the retrieve_price_for_a_symbol method by writing same method in test class but when i call it, the call is happening to method in main class not in the test class.

How do I add that method to meta class from test and how do i call it? Please help.

1
  • Why do you want to mock the method you are explicitly testing? If you mock the method, you are not testing the implementation of it, which renders the test obsolete. Commented Oct 3, 2013 at 6:49

2 Answers 2

2

Instead of re-defining the method inside, you need to mock it out.

Replace the method definition inside the test with

@asset.expects(:retrieve_price_for_a_symbol).with('YHOO').returns(33.97)
Sign up to request clarification or add additional context in comments.

3 Comments

its says undefined method expects
You need to install mocha gem first. Type in terminal $ gem install mocha and then in your test code require "mocha/setup"
I want to perform the operation without using frameworks. In groovy there is a where we can redefine a method in test class and call it using main class object by using @classobject.metaclass.method_name is there a similar thing in ruby as well?
2

Assuming you don't really want to mock the method you're testing...

You are currently defining your mock on the instance of the test class. You can add your mock directly to the @asset object:

def test_retrive_price_for_YHOO
  def @asset.retrieve_price_for_a_symbol(symbol)
    33.77
  end

  assert_equal(33.97, @asset.retrieve_price_for_a_symbol('YHOO'))
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.