Using Mocha in Rails to test form_for path generation
Using the resource routes, you can do things like url_for(@apple) to get a url to that particular resources "show" method. However, in testing, using Mocha to mock up my objects, I'm having trouble generating the appr开发者_开发百科opriate path to the resource.
E.g. Consider this example of how url_for routes:
@apple.id # => 4
url_for(@apple) #=> domain.com/apples/4
This is equivalent to the more verbose:
url_for(:controller => 'apples', :id => 4, :method => :show)
In attempting to test my views, I use Mocha to mock up my objects.
Apple.stubs(:color => 'red') # returns a MochaExpectation, rather than an instance of Apple.
So in my test:
assigns[:apple] = @apple = Apple.stubs(:color => 'red')
url_for(@apple) #=> raises undefined method `mocha_expectation_path'
How can I get approach this? It seems either stubs needs to return an Apple < ActiveRecord::Base or url_for needs to understand what to do with a mocha_expectation.
You are using Mocha incorrectly.
If you want an instance of a traditional mocha object :-
@apple = stub('apple', :colour => 'red')
If you want to stub specific methods on a real object :-
@apple = Apple.new
@apple.stubs(:colour => 'red')
精彩评论