【问题标题】:How to isolate fixtures to specific Rails tests如何将固定装置隔离到特定的 Rails 测试
【发布时间】:2015-11-05 22:30:19
【问题描述】:

如何将固定装置的使用与特定测试隔离开来?

在我的设置中,我的一些测试依赖于夹具数据,而有些则不依赖,因此在 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

【问题讨论】:

    标签: ruby-on-rails testing fixtures


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多