无法在Rspec测试中登录用户(设计宝石)

时间:2013-02-18 18:32:00

标签: ruby-on-rails devise rspec-rails

我无法找到解决问题的方法:无法在rspec测试中登录用户

我尝试了此代码,请点击此链接 - https://github.com/plataformatec/devise/wiki/How-To:-Stub-authentication-in-controller-specs

require 'spec_helper'
require 'factory_girl_rails'

describe "ololo" do

it "blocks unauthenticated access" do

 user = User.create(email: "lol@mail.com", password: "123456")
 request.env['warden'].stub(:authenticate!).
 and_throw(:warden, {:scope => :user})

  visit "/tasks"

  page.should have_content("Signed in successfully.")

end
end

/ 错误 /

Failure/Error: page.should have_content("Signed in successfully.")
   expected there to be text "Signed in successfully." in "Task App Home Login You need to sign in or sign up before continuing. Sign in Email Password Remember me Sign upForgot  

你的密码?任务应用程序由Denys Medynskyi“

也试过这个链接 - http://codingdaily.wordpress.com/2011/09/13/rails-devise-and-rspec/

设计维基教程对我来说也不起作用。

拜托,我几乎没有陷入困境。帮帮我。

1 个答案:

答案 0 :(得分:1)

在没有看到您的错误消息的情况下,我的一个可能原因是您创建了用户来测试数据库的硬记录。您可能已经运行过此测试一次,因此第二次创建失败,因为存在具有相同电子邮件的记录。

你需要FactoryGirl。为什么不使用FactoryGirl来创建夹具数据?

spec/factories/user.rb

FactoryGirl.define do
  factory :user do
    email: "lol@mail.com"
    password "123"
  end
end

在你的测试中,写下

FactoryGirl.create(:user)

添加

与tut相比,你缺少两个步骤:

  1. 您需要使用FactoryGirl替换硬创建的记录,如上所述。
  2. 在访问私人页面之前,您需要执行sign_in步骤。
  3. 如果你在测试后清除数据库,那么你可能会对#2很好。无论如何,建议使用工厂数据而不是硬数据。