如何在spec_helper中使用mock_model(用于Authlogic)

时间:2011-07-06 17:01:03

标签: rspec2

我正在升级到rails 3和rspec 2。

我在spec_helper中收到错误“undefined method`mock_model'”。我的current_user方法为authlogic设置了一个模拟用户并生成了这个错误。

我的规范助手看起来像这样

require 'authlogic/test_case'
require 'shoulda'
require 'helpers'

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}
Dir[Rails.root.join("spec/factories/**/*.rb")].each {|f| require f}

RSpec.configure do |config|
  config.mock_with :rspec
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
end

module LoginHelper
   include Authlogic::TestCase

   def login_user person
     activate_authlogic
     UserSession.create(...)
   end
end
include LoginHelper


def current_user(stubs = {})
  @current_user ||= mock_model("User", stubs)
end

def user_session(stubs = {}, user_stubs = {})
  @current_user ||= mock_model(UserSession, {:user => current_user(user_stubs)}.merge(stubs))
end

def login(session_stubs = {}, user_stubs = {})
  UserSession.stub!(:find).and_return(user_session(session_stubs, user_stubs))
end

def logout
  @user_session = nil
end

1 个答案:

答案 0 :(得分:0)

mock_modelrspec-rails gem中的RSpec 2中定义。如果您将rspec-rails添加到Gemfile中,则应自动将其包含在内以用于所有其他必需的RSpec 2宝石。

您还应注意mock_model不适用于UserSession,因为它继承自Authlogic::Session::Base,而不是ActiveModel。您可以通过添加到UserSession模型来修复此问题:

class UserSession < Authlogic::Session::Base
  extend ActiveModel::Naming
end