使用Authlogic进行集成测试?
对于我的生活,我不明白为什么Authlogic没有在这个集成测试中登录我。 我没有遇到任何问题,Authlogic使用此代码在function测试中登录我。 根据authlogic rdocs( http://tinyurl.com/mb2fp2 ),模拟登录状态在function和集成测试中是相同的,所以我很困惑。 任何帮助深表感谢!
class TipsController [:destroy, :undelete] def destroy @tip = Tip.find(params[:id]) if can_delete?(@tip) @tip.destroy set_flash("good", "Tip deleted. Undo?") respond_to do |format| format.html { redirect_to city_path(@tip.city)} end else set_flash("bad", "Seems like you can't delete this tip, sorry.") respond_to do |format| format.html { render :action => "show", :id => @tip} end end end end class DeleteTipAndRender @tip.id end should_redirect_to("city_path(@tip.city)"){city_path(@tip.city)} end end end
基于user_sessions_controller
create
方法中的代码,该方法获取了登录凭据的哈希值,我能够在集成测试中使其像这样工作:
UserSession.create(:email => 'someone@example.com', :password => 'password')
但不是:
UserSession.create(@user)
我也在与Shoulda一起使用Authlogic(但是在factory_girl的顶部)。
我的function测试看起来像:
require 'test_helper' class LoansControllerTest < ActionController::TestCase [...] context "as a signed-in user, with an active loan" do setup do @user = Factory(:user) @user_session = UserSession.create(@user) @loan = Factory(:loan, :ownership => Factory(:ownership, :user => @user)) end context "on GET to :index" do setup do get :index end should_respond_with_success end end end
实际上,您可以将有效用户传递给UserSession,它也在rdoc中。 您还应该避免在每个控制器测试中调用activate_authlogic:
ENV["RAILS_ENV"] = "test" require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'test_help' class ActiveSupport::TestCase [...] # Add more helper methods to be used by all tests here... include Authlogic::TestCase def setup activate_authlogic end end
我发现对于集成测试我需要通过post登录:
setup do post 'user_session', :user_session => {:email => 'someone@example.com', :password => 'password'} end
这会正确设置会话,而上述方法仅适用于function测试。
是的,我本周发现使用rspec:在function规格中,您可以使用UserSession.create(@user)
模拟登录。 但是如果你在集成规范中尝试它,它就不起作用。 为了从集成规范登录,我发现我必须驱动表单(使用webrat),这显然会成为Facebook和OpenID登录等问题。
我无法使用已接受的答案,但是很接近。 我不得不在函数的末尾添加惊叹号:
UserSession.create!(@user)
它正在使用Ruby v3.2.18和Authlogic v3.4.2。 谢谢你指出我正确的方向。
我正在使用Cucumber和James的解决方案以及以下修复程序为我工作:
对于在Google和大正义中找到此post的人 – 您必须在用户模型中设置persitence_token
属性。 例如,你可以调用@user.reset_persistence_token!
一切都刚刚开始工作。 🙂
我遇到了同样的问题,我可以通过手动登录来修复它(正如其他人已经回答的那样)
另外,我必须修复我的cookie域 :
Rails使用www.example.com
进行测试,因为我在我的application.rb
(通过config.cookie_domain
)中将cookie域设置为不同的值,因此无法从后续请求访问登录后创建的会话cookie。
设置正确的cookie域后,一切都恢复正常。
看看rdoc 。