ActionView::TemplateError: undefined method `mocha_mock_path'
Check that you also stub the
class method.
stub(:title => 'a title', :class => News)
ActionView::TemplateError: undefined method `mocha_mock_path'
class method.
stub(:title => 'a title', :class => News)
...always beware of cases where some code invokes more than one method on the same object...
And inside the test case you change the constant to what you need and restore it after the test ends:
class Module
def redefine_const(name, value)
__send__(:remove_const, name) if const_defined?(name)
const_set(name, value)
end
end
But if you can control the code that uses the constant there's a more clean way. Just wrap it in a method and get the constant through the method. During testing you just mock the method:
Object.redefine_const(:RAILS_ENV, 'production')
And then in your test you just do a normal expectation:
class A
def rails_env
RAILS_ENV
end
#...some more code that gets the constant RAILS_ENV using the method rails_env...
end
You could even have some module that wraps all useful constants in your app, so constant dependent code gets easily testable and clean.
A.any_instance.expects(:rails_env).returns 'production'
Excellent posts here and here by Jay Fields where he gives an alternative to use singleton classes.
Instead of doing this:You do this:
class << self
def hi
puts 'Hi'
end
end
mod = Module.new do
def hi
puts 'Hi'
end
end
extend mod