如何在AuthLogic控制器规格中使用模拟模型? [英] How can I use mock models in AuthLogic controller specs?
问题描述
我试图写一个控制器的规格,而不使用夹具(而是使用模拟模型)。此控制器要求用户登录,我将使用 AuthLogic ,然后按作者建议。
I am trying to write specs for a controller without using fixtures (instead employing mock models). This controller requires a user to be logged in, for which I'm employing AuthLogic, following the author's recommendations.
describe UsersController do
def mock_user(stubs={})
@mock_user ||= mock_model(User, stubs)
end
context 'when logged in' do
before { activate_authlogic }
it "exposes the logged-in user as @user in response to GET (show)" do
UserSession.create(mock_user)
...
end
...
end
...
end
这些示例都在 UserSession.create ..)
,报告以下内容:
These examples all fail at the line UserSession.create(...)
, reporting to the effect of:
Mock 'User_1005' received unexpected message :changed? with (no args)
我不知道如何解决这个问题。是嘲笑与:改变? => false 适当?
I'm not sure how to resolve this; is mocking with :changed? => false
appropriate?
推荐答案
Iain发布了解决方案使用模拟对象与AuthLogic 。要重新表达,以下帮助者进入 spec_helpers.rb
:
Iain posted a solution to using mock objects with AuthLogic. To rephrase, the following helpers go into spec_helpers.rb
:
def current_user(stubs = {})
@current_user ||= mock_model(User, stubs)
end
def user_session(stubs = {}, user_stubs = {})
@current_user_session ||= 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
我已经将它纳入我的规格,是希望。我有工作控制器规范,为登录的用户展开模拟模型,所以现在,当我向User添加一个字段时,它们不会全部中断。 Iain在规范中实现这个例子是:
I've incorporated this into my specs, and I find it does exactly what I was hoping. I have working controller specs that exploy mock models for the logged-in user, so now they don't all break when I add a field to User. Iain's example of implementing this in a spec is as:
describe SecretsController do
before { login }
it "should be very very secret!"
end
我讨厌回答我自己的问题,但这是我正在寻找的答案;我只是没有找到足够早。
P.S. I hate to answer my own question, but this is the answer I was looking for; I just didn't find it early enough.
这篇关于如何在AuthLogic控制器规格中使用模拟模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!