我会完全废弃实例变量并使用助手。GroupsHelper
从in之类的东西开始app/helpers/groups_helper.rb
。
module GroupsHelper
def user_group
@user_group ||= group_from_cookie
end
def user_group=(group)
@user_group = group
end
private
def group_from_cookie
group_uid = cookies[:user_group]
LearningGroup.find_by_uid group_uid unless group_uid.nil?
end
end
然后include
在ApplicationController
.
class ApplicationController < ActionController::Base
include GroupsHelper
# ...
end
现在,spec/support
为您的测试定义一个助手。
include ApplicationHelper
def join_group group_uid
# whatever preparation you may need to do as well
cookies[:user_group] = group_uid
end
测试可能类似于:
it 'does something awesome' do
join_group 'my awesome group id'
# ...
expect(your_subject).to be_awesome
end
当您运行测试时,user_group
将返回由您已经分配给 cookie 对象的值确定的值。
这还有一个好处,那就是只调用而不是在多个测试中到处join_group
存根。LearningGroup