Rspec和Capybara未初始化常数

时间:2015-04-09 13:55:38

标签: ruby testing rspec capybara bdd

我在非RoR项目中使用Rspec 3.2和Capybara 2.4。我正在尝试使用Capybara gem提供的功能模式进行测试。

$ cat .rspec                                                                                    
--color
--require spec_helper

$ cat spec/features/test_spec.rb                                                                
feature 'login' do
    username ="rspec#{Time.now.to_i}"
    valid_email = "#{username}@gmail.com"

    scenario 'with valid email' do
      sign_up_with  valid_email, 'pwd', 'pwd', username
      expect(page).to have_content('LOGOUT')
    end
  end

$ cat spec/support/session_helper.rb                                                            
module SessionHelper
  def sign_up_with(email, password, confirm_password, username)
      visit '/signup'
      fill_in 'email', with: email
      fill_in 'password', with: password
      fill_in 'passconf', with: confirm_password
      fill_in 'username', with: username
      click_button 'submit'
  end
end

$ cat spec/spec_helper.rb                                                                       
require 'capybara/rspec'
Capybara.default_driver = :selenium
RSpec.configure do |config|
  ...
  config.include SessionHelper, type: :feature
  ...
end

这是一个非RoR项目,当我运行测试时出现此错误:

$ rspec                                                                                         
spec/spec_helper.rb:26:in `block in <top (required)>': uninitialized constant SessionHelper (NameError)

在在线文档中有很多例子,我已经像我的例子一样构建了我的文件,但它不起作用。

1 个答案:

答案 0 :(得分:1)

我在所有项目中处理这个问题的方式是这样的:

需要所有支持文件:

spec_helper.rb

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

然后您的 spec / support / session_helper.rb 应如下所示:

module SessionHelper
  def sign_up_with(email, password, confirm_password, username)
      visit '/signup'
      fill_in 'email', with: email
      fill_in 'password', with: password
      fill_in 'passconf', with: confirm_password
      fill_in 'username', with: username
      click_button 'submit'
  end
end

RSpec.configure do |config|
  # Remove the equivalent line from spec_helper.rb
  config.include(SessionHelper)
end