【问题标题】:How to use minitest fixtures in Cucumber steps?如何在 Cucumber 步骤中使用 minitest 固定装置?
【发布时间】:2013-12-06 12:38:05
【问题描述】:

如何在 Cucumber 步骤中使用 stock minitest 附带的固定装置?

说,我有`test/fixtures/users.yml:

harry:
  email: harry@hogwards.edu.uk
  password: caputdraconis

在 minitest 中,这将用于例如@user = users(:harry)。但不能在 Cucumber 中使用:undefined method 'users' for #<Cucumber::Rails::World:0xaf2cd1c> (NoMethodError).

如何在 Cucumber 中提供固定装置及其助手?这是一个好主意吗?

【问题讨论】:

  • 你找到方法了吗?
  • @AlexanderSupertramp,不,还没有。

标签: ruby-on-rails cucumber minitest fixtures


【解决方案1】:

把它放到你的features/support/env.rb:

module FixtureAccess
  def self.extended(base)
    ActiveRecord::FixtureSet.reset_cache
    fixtures_folder = File.join(Rails.root, 'test', 'fixtures')
    fixtures = Dir[File.join(fixtures_folder, '*.yml')].map {|f| File.basename(f, '.yml') }
    fixtures += Dir[File.join(fixtures_folder, '*.csv')].map {|f| File.basename(f, '.csv') }

    ActiveRecord::FixtureSet.create_fixtures(fixtures_folder, fixtures)    # This will populate the test database tables

    (class << base; self; end).class_eval do
      @@fixture_cache = {}
      fixtures.each do |table_name|
        table_name = table_name.to_s.tr('.', '_')
        define_method(table_name) do |*fixture_symbols|
          @@fixture_cache[table_name] ||= {}

          instances = fixture_symbols.map do |fixture_symbol|
            if fix = ActiveRecord::FixtureSet.cached_fixtures(ActiveRecord::Base.connection, table_name).first.fixtures[fixture_symbol.to_s]
              @@fixture_cache[table_name][fixture_symbol] ||= fix.find  # find model.find's the instance
            else
              raise StandardError, "No fixture with name '#{fixture_symbol}' found for table '#{table_name}'"
            end
          end
          instances.size == 1 ? instances.first : instances
        end
      end
    end
  end
end

World(FixtureAccess)

我的灯具位于test/fixtures,因为我使用的是 Minitest,所以如果您使用 RSpec,您应该更新您的 fixtures_folder 以匹配您的灯具的位置。

在此之后,您可以执行以下操作:

When(/^a user exists$/) do
  users(:harry)
end

在您的步骤定义中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多