Rails 5.1系统测试夹具和数据库清理

时间:2017-10-25 15:30:22

标签: ruby-on-rails

rails 5.1系统测试是否应该在每次测试之间使用原始夹具数据重置测试数据库?

即使在完全不同的测试类之间,也不会发生这种情况。我的系统测试之一是:

test 'delete thing' do
  # deletes a thing from the fixture data
end

然后我有另一个测试,看看是否有东西

test 'view thing' do
  # tries to view the thing
end

如果首先运行“查看事物”测试,则测试通过。如果首先运行“删除事物”测试,那么当我的系统测试试图查看该事物时,它就会失败。

我认为Rails系统测试正在重置数据,就像所有其他测试一样。这不是这种情况吗?我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

我今天早上刚刚处理过这个问题,我想我已经弄明白了。

这个关于灯具的文档对我有所帮助:http://api.rubyonrails.org/v5.1.4/classes/ActiveRecord/FixtureSet.html

对我而言,当我的测试涉及修改数据(如添加和删除记录)时,我必须确保使用 ModelName.method 方法与测试数据库交互,不会更改您的灯具。起初我使用 fixture_name.method 进行阅读和写作,这导致了意想不到的结果。

例如,使用 Blog 的模型和一个夹具文件 blogs.yml ,其中包含一条记录(哈希到key =:one):

test "view blog" do
  get blog_path blogs(:one).id
  assert_response :success

  *OR*
  get blog_path Blog.first.id
  assert_response :success
end

但如果修改,坚持使用第二种方法:

test "delete blogs" do
  assert_equal 1, Blog.count
  assert_equal Blog.first.id, blogs(:one).id
  Blog.destroy_all
  assert_equal 0, Blog.count
  assert_raises(NoMethodError) { Blog.first.id }
  assert_nothing_raised { blogs(:one).id }
end

test "before_or_after_delete_blogs" do
  assert_equal 1, Blog.count
  assert_equal Blog.first.id, blogs(:one).id
end

这两个都应该通过。

如果我的解释不合适,请道歉。如果是这样的话,你能为你的例子提供更多的背景吗?

答案 1 :(得分:0)

我使用gem database_cleaner。不确定这是否是您问题的答案。

这还有帮助吗?     rake db:test:prepare

不太确定你的问题,但希望有帮助

相关问题