我无法让我的测试工作,并且想知道是否有人有任何指针。我正在测试我的用户编辑页面,以便您必须登录才能查看和编辑用户配置文件。在authlogic文档之后,以下是相关代码:
class ApplicationController < ActionController::Base
helper_method :current_user_session, :current_user
private
def current_user_session
return @current_user_session if defined?(@current_user_session)
@current_user_session = UserSession.find
end
def current_user
return @current_user if defined?(@current_user)
@current_user = current_user_session && current_user_session.user
end
def require_current_user
unless current_user
flash[:error] = 'You must be logged in'
redirect_to sign_in_path
end
end
end
class UsersController < ApplicationController
before_filter :require_current_user, :only => [:edit, :update]
...
end
describe "GET 'edit'" do
before(:each) do
@user = Factory(:user)
UserSession.create(@user)
end
it "should be successful" do
# test for /users/id/edit
get :edit, :id => @user.id
response.should be_success
end
我使用浏览器测试它并且它可以工作。您必须登录才能编辑您的个人资料,但它在我的rspec测试中不起作用。
我觉得它与mock controller有关,但我无法弄清楚如何。我还阅读了test case,但仍无法使其发挥作用。
请帮助,非常感谢!!!
答案 0 :(得分:2)
您可以在ApplicationController上存根current_user方法,如下所示:
fake_user = controller.stub(:current_user).and_return(@user) #you could use a let(:user) { FactoryGirl.create(:user) } instead of before_each
get :edit, :id => fake_user.id
response.should be_success