1

I'm trying to test a rake task which scrapes my site and pushes the content to an elasticsearch server; the task works fine. However the test is failing because in one view I randomly pick some values like this:

[:breast,:ovarian][rand(2)]
(rand * 4)-2
rand(Date.new(2006)..Time.now.to_date)

Which means I need to stub rand. In order to stub rand I need access to the class-instance that is calling it, which in this case is whatever class is rendering my view. Calling puts self.class Just returns Class and an id, so how can I get ahold of the instance in order to stub it?

I could pass these values into the view from the controller as instance variables, if getting ahold of the controller would be easier.

Camden Narzt
  • 2,271
  • 1
  • 23
  • 42

1 Answers1

0

long story short: it would be better to extract the offending logic and place it in a helper. This way you will be able to stub it easily, and even unit-test it if needed. Moreover this improves the overall quality of your code (no logic should belong to the view).

also, rand is a method from Kernel, so it is already "stubable"

Community
  • 1
  • 1
m_x
  • 12,357
  • 7
  • 46
  • 60
  • I don't see how that would help me as I need the view rendering class to stub the helper that gets mixed in. I'm not using Rspec, so no it's not stubable globally: http://stackoverflow.com/questions/31600968/how-can-i-stub-rand-in-minitest – Camden Narzt Jul 24 '15 at 15:39
  • 1
    sorry, it did not occur to me that your were speaking about an integration test. IMHO the logic itself should be tested in unit test, and integration test should only test collaboration between components (i.e. expect this method on this object to be called). So unit-test the helper, and assert it was called in the integration test, was my advice. See http://stackoverflow.com/questions/2146040/rails-how-do-i-write-tests-for-a-ruby-module on how to unit test a module. – m_x Jul 27 '15 at 12:19