【问题标题】:getting past authentication with capybara in rails application在 Rails 应用程序中通过 capybara 的身份验证
【发布时间】:2015-01-17 17:06:49
【问题描述】:

我正在尝试在 ruby​​ on rails 应用程序上使用 capybara 来进行一些内容测试,并且我正在使用设计 gem 来实现用户身份验证。我无法登录我的应用程序来执行我的测试用例。

最初,我的场景如下:

scenario "User arrives at main page" do 
    visit "purchase_orders#index"
    page.should have_content("All")
    # some more tests and checks
end

其中 purchase_orders#index 是经过身份验证的根,其中显示了用户的采购订单。 但是当我运行测试时,我得到了以下错误:

expected to find text "All" in "Log in to manage your orders * Email * Password Forgot your password? Remember me Sign up • Didn't receive confirmation instructions? About Us • Contact Us • 

这告诉我它没有通过登录页面。接下来,我尝试在运行测试之前将以下内容添加到我的场景中,以使其登录:

    visit "purchase_orders#index"
    fill_in('Email', :with => 'username@gmail.com')
    fill_in('Password', :with => 'password')
    click_button('Log in')

其中用户名和密码是实际创建的帐户,但再次失败并且无法通过登录页面。最后,我尝试添加一个 before(:each) 方法,如下所示,尝试为测试用例登录用户:

    before(:each) do
    visit "users/sessions#new"
    fill_in('Email', :with => 'nico.dubus17@gmail.com')
    fill_in('Password', :with => 'password')
    click_button('Log in')
end

同样,这对我不起作用。所以我的问题是:通过登录页面进入实际应用程序的最佳实践和语法是什么?我一直在寻找有关此的文档和答案,但没有找到任何东西。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby devise capybara


    【解决方案1】:

    找到了答案。我将warden gem安装到(gem'warden')和工厂女孩gem(gem“factory_girl_rails”,“~> 4.0”)并运行捆绑安装。然后,我在 spec 文件夹的 factory.rb 文件中创建了一个带有 factory girl 的用户夹具,如下所示:

        # This is a user factory, to simulate a user object
    FactoryGirl.define do
        factory :user, class: User do
            first_name "John"
            last_name  "Doe"
            email "nico_dubus@hotmail.com"
            encrypted_password "password"
        end
    end
    

    在我的 rails 帮助文件中,我添加了这一行以便能够使用 FactoryGirl 的方法,而无需每次都在类上调用它:

      config.include FactoryGirl::Syntax::Methods
    

    之后,我将这些行添加到我的水豚测试页面的顶部:

    include Warden::Test::Helpers
    Warden.test_mode!
    

    最后,我构建了一个在测试范围内使用的用户对象:

        user = FactoryGirl.build(:user)
    

    而且每当我需要登录时,我都会使用warden的登录方法

            login_as(user, :scope => :user)
    

    瞧!

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-06
      • 2017-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多