如何将灯具与特定的Rails测试隔离开来

时间:2015-11-05 22:30:19

标签: ruby-on-rails testing fixtures

如何将灯具的使用与特定测试隔离开来?

在我的设置中,我的一些测试依赖于夹具数据,而有些测试依赖于夹具数据,因此在test_helper.rb中使用fixtures :all加载所有夹具的默认设置会破坏我的测试。

需要空行为主义者表的示例集成测试:

require 'test_helper'

class WelcomeFlowTest < ActionDispatch::IntegrationTest
  test "when no user is found start welcome flow" do
    get "/"
    follow_redirect!
    assert_response :success

    post "/setup", {
      behaviorist: { name: "Andy", email: "andy.bettisworth@accreu.com" },
      habit: { name: "Interval running", on_monday: false, on_tuesday: true, \
               on_wednesday: false, on_thursday: true, on_friday: false, \
               on_saturday: true, on_sunday: false }
    }
    assert_response :success
    assert_equal 1, Behaviorist.count
    assert_equal 1, Habit.count
  end
end

我的单元测试需要行为主义设备:

require 'test_helper'

class BehavioristTest < ActiveSupport::TestCase
  test "validates uniqueness of :name" do
    andy = Behaviorist.new(name: "Andy", remote_ip: "127.0.0.1")
    assert_not run.valid?
    assert_match /has already been taken/, andy.errors[:name].join
  end
end

1 个答案:

答案 0 :(得分:1)

通过对Rails如何实现灯具的一点挖掘,我看到灯具一旦加载,就会通过事务与每个TestCase中的变化隔离开来。我的工作解决方案是删除在test_helper.rb中加载fixtures :all。然后,对于需要灯具的每个测试,我覆盖默认使用事务夹具,加载特定灯具,然后在拆卸时将其删除。

单个TestCase的隔离装置示例:

require 'test_helper'

class BehavioristTest < ActiveSupport::TestCase
  self.use_transactional_fixtures = false
  fixtures :behaviorists
  teardown :delete_behaviorists

  test "validates uniqueness of :name" do
    andy = Behaviorist.new(name: "Andy", remote_ip: "127.0.0.1")
    assert_not run.valid?
    assert_match /has already been taken/, run.errors[:name].join
  end

  private

  def delete_behaviorists
    Behaviorist.delete_all
  end
end