【问题标题】:Rails Controller testing: Does database state change persist after success of test?Rails 控制器测试:测试成功后数据库状态更改是否持续存在?
【发布时间】:2011-03-12 05:41:19
【问题描述】:

我正在使用 ActionController::TestCase (下面的代码) 测试 BranchController 的创建方法。我检查对象是否是通过调用 find_by_name 方法创建的(假设名称在这里是唯一的)。 测试成功运行,但是当我在 mysql db 中检查相同的记录时,它不存在。

    class Security::BranchControllerTest < ActionController::TestCase
      test "the create" do
     post(:create, :branch => {:name => "test branch", :details=> "test branch details"})

     #replace find with where searching with all of fields 
     assert_not_nil Company::Branch.find_by_name("test branch") 
      end   
    end

【问题讨论】:

    标签: ruby-on-rails database testing controller persistence


    【解决方案1】:

    如果您使用支持事务的数据库(现在大多数情况下),rails 测试默认情况下会在运行每个测试之前设置一个保存点,并在最后进行回滚。

    这意味着插入实际上正在发生,但结果在测试之外是不可见的。

    您应该会在测试日志中看到保存点和回滚操作。

    如果你想禁用这个,你可以添加

    self.use_transactional_fixtures = false

    在你的测试类中,或者通过添加类似的东西来为你的所有测试修补它

    class ActiveSupport::TestCase
      self.use_transactional_fixtures = false
    end
    

    在你的 test_helper 类中。

    通常禁用此功能可能不是一个好主意,因为这是保持测试独立性的好方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多