【问题标题】:Where/how to include helper methods for capybara integration tests在哪里/如何包含用于 capybara 集成测试的辅助方法
【发布时间】:2012-01-01 19:34:19
【问题描述】:

我正在使用 capybara 进行集成/验收测试。它们位于 /spec/requests/ 文件夹中。现在我有一些在验收测试期间使用的辅助方法。一个示例是 register_user,它看起来像这样

def register_user(user)
  visit home_page
  fill_in 'user_name', :with => user.username
  fill_in 'password', :with => user.password
  click_button 'sign_up_button'
end

我想在几个不同的验收测试中使用这种方法(它们在不同的文件中)。包含此内容的最佳方式是什么?我试过把它放在spec/support/,但它对我没有用。在花了一些时间之后,我意识到我什至不知道这是否是一种好方法,所以我想我会在这里问。

注意:我使用的是 rails 3、spork 和 rspec。

【问题讨论】:

    标签: ruby-on-rails ruby rspec capybara


    【解决方案1】:

    将你的助手放到 spec/support 文件夹中并执行如下操作:

    规范/支持/:

    module YourHelper
      def register_user(user)
        visit home_page
        fill_in 'user_name', :with => user.username
        fill_in 'password', :with => user.password
        click_button 'sign_up_button'
      end
    end
    
    RSpec.configure do |config|
      config.include YourHelper, :type => :request
    end
    

    【讨论】:

    • 你什么时候使用规范/支持与规范/助手?
    • @cman77 spec/helpers 用于测试应用程序/帮助程序,spec/support 文件用于您要在规范中使用的模块和配置
    • spec/support里面的文件不是都自动加载了吗?
    • @Gerep spec/support 会自动加载。但这不会使 RSpec 自动使用助手。
    • spec/support 不再自动加载,spec_helper.rb 中有一个注释掉的行可用于将文件包含在支持目录中:Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
    【解决方案2】:

    我使用了@VasiliyErmolovich 给定的解决方案,但我更改了类型以使其工作:

    config.include YourHelper, :type => :feature
    

    【讨论】:

    • Same here ... 那是如果您在规范/功能与规范/请求中进行测试
    【解决方案3】:

    Ruby 的显式方式

    使用include:

    # spec/support/your_helper.rb
    class YourHelper
      def register_user(user)
        visit home_page
        fill_in 'user_name', :with => user.username
        fill_in 'password', :with => user.password
        click_button 'sign_up_button'
      end
    end
    
    describe MyRegistration do
      include YourHelper
    
      it 'registers an user' do
        expect(register_user(user)).to be_truthy
      end
    end
    

    【讨论】:

    • 好的,这将帮助程序与其他测试隔离开来。但是,如果它是通常需要的 Capybara/Selenium 特定的助手怎么办?就像我在所有测试文件中都需要的一些 JS 包装器一样。而且我不想通过MyHelpers::my_js_helper 调用它,但我希望它像find 一样容易访问。
    • @Nakilon 它是普通的红宝石,你可以用它重构你的规范/代码/DSL/capybara/selenium/whatever。因为include 到处都像mixin 一样工作。 Find 方法已经存在于 capybara 中。但这并不妨碍创建另一种方法,例如content_find 使用 mixin 方法。
    • RSpec 的 include 和 exclude -- 虽然它们看起来像普通的 Ruby,但实际上它们是为过滤能力而定制的,甚至可能更多。虽然 Capybara 回购中有 no "def include",但也许还有其他我不知道的东西。
    • 哦,我错了。在describe 内部,include 方法是纯Ruby。但是问题仍然存在,我需要将这一行放在我需要的每个上下文中,在几十个文件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多