我在lib目錄下創建了一個模塊,我可以在我的Rails應用程序中隨意調用它包含的各種方法(在添加include ModuleName之後),沒有任何問題。Rails - 爲什麼我不能在測試中使用我在模塊中創建的方法?
但是,當涉及到測試時,他們抱怨沒有這樣的方法存在。我試圖將模塊包含到我的測試助手中,但沒有運氣。任何人都可以幫忙
4) Error:
test_valid_signup_redirects_user_to_spreedly(UsersControllerTest):
NoMethodError: undefined method `spreedly_signup_url' for SpreedlyTools:Module
/test/functional/user_controller_test.rb:119:in `test_valid_signup_redirects_user_to_spreedly'
module SpreedlyTools
protected
def spreedly_signup_url(user)
return "blahblah"
end
end
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
include SpreedlyTools
....
end
ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
class ActiveSupport::TestCase
include SpreedlyTools
....
end
require File.dirname(__FILE__) + '/../test_helper'
require 'users_controller'
# Re-raise errors caught by the controller.
class UsersController; def rescue_action(e) raise e end; end
class UsersControllerTest < ActionController::TestCase
....
def test_valid_signup_redirects_user_to_spreedly
get :new
assert_response :success
post :create, :user => {:first_name => "bobby",
:last_name => "brown",
:email => "[email protected]",
:email_confirmation => "[email protected]",
:password => "bobby1",
:password_confirmation => "bobby1"}
assert_response :redirect
user = assigns(:user)
assert_redirected_to SpreedlyTools.spreedly_signup_url(user)
end
end
我的初衷並不是將這些方法作爲用戶類的一部分。相反,它們只是整個應用程序可用的一般方法。事後看來,它看起來應該重構,並且讓這種特殊的方法成爲一流的課程的一部分。但是,一般情況下,我應該能夠在我的任何測試中調用我在lib中的模塊中定義的方法,而無需添加任何包含/要求或其他代碼? – robodisco 2009-12-01 14:21:05
只有遵循Ruby自動加載規則。 – 2009-12-01 15:34:03
Re。第一條評論:我想補充一點,如果你有可能需要在你的應用程序的其他地方使用spreedly_signup方法,你可能需要考慮將它作爲一個單獨的模塊,並單獨測試SpreedlyTools ...沒有空間來解釋如何在評論中做到這一點,雖然...有關於stackoverflow解釋如何做到這一點的幾個很好的問題。 – btelles 2009-12-01 20:27:49