没有用Capybara测试Devise

时间:2011-07-04 22:37:25

标签: ruby-on-rails-3 testing capybara

我正在使用Devise构建一个Rails 3应用程序,使用Capybara进行UI测试。以下测试失败:

class AuthenticationTest < ActionController::IntegrationTest

  def setup
    @user = User.create!(:email => 'test@example.com', 
                         :password => 'testtest', 
                         :password_confirmation => 'testtest')
    @user.save!
    Capybara.reset_sessions!
  end

  test "sign_in" do
    # this proves the user exists in the database ...
    assert_equal 1, User.count
    assert_equal 'test@example.com', User.first.email

    # ... but we still can't log in ...
    visit '/users/sign_in'
    assert page.has_content?('Sign in')
    fill_in :user_email, :with => 'test@example.com'
    fill_in :user_password, :with => 'testtest'
    click_button('user_submit')

    # ... because this test fails
    assert page.has_content?('Signed in successfully.')
  end

end

......但我不明白为什么。从代码中可以看出,用户正在数据库中创建;我正在使用相同的方法来创建用户,就像我在seeds.rb中所做的那样。

如果我通过调试器运行测试,我可以在数据库中看到用户并验证页面是否正在加载。但是身份验证仍然失败;我可以验证这一点,因为如果我更改断言以测试失败案例,则测试通过:

# verify that the authentication actually failed
assert page.has_content?('Invalid email or password.')

我习惯了Rails 2,&amp;使用Selenium进行这种测试,所以我怀疑我正在做一些愚蠢的事情。有人可以指点我在正确的方向吗?

3 个答案:

答案 0 :(得分:24)

我遇到了同样的问题,发现a thread with a solution

RSpec.configure do |config|
  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

end

要使DatabaseCleaner工作,您需要包含database_cleaner gem。如果您之前没有使用它,则可能需要rake db:test:prepare才能重新运行测试。我希望这也适合你!

答案 1 :(得分:3)

我之前遇到过类似的问题。直接设置密码有一些奇怪的效果,因为它应该加密并存储在盐中 - 有时它对我有用,有时则不适用。我很难记住哪些具体案例存在问题。我按照这个顺序(为简单起见)推荐以下内容

  • 验证密码字段是否正确填写并作为正确的参数传递(如果您使用的是Devise的自动生成视图并且未触及它,则不需要)
    • 如果您的网站可以在开发模式下运行(即没有登录错误),那么只需启动它并手动登录
    • 如果没有,请在debugger中插入sessions_controller作为第一行。然后检查params并确保密码正确且位于params[:user][:password]
      如果您没有覆盖Devise的sessions_controller,那么您可以使用bundle show devise找到您的Devise路径。然后在create
    • 中查找(devise path)/app/controllers/devise/sessions_controller.rb操作
  • 更改测试设置以通过Web界面创建用户,以确保正确设置密码,然后再次尝试运行测试

答案 2 :(得分:1)

我遇到的问题与你的设置非常相似。就我而言,在初始化程序中切换到ActiveRecord会话解决了这个问题。

此外,请务必致电@ user.skip_confirmation!如果你正在设计中使用“确认”模块。

相关问题