简体   繁体   English

RSpec Rails测试数据

[英]RSpec Rails Test Data

I'm trying to optimise my specs a bit. 我正在尝试优化我的规格。 I usually have a problem creating test data for nested resources and users. 我通常在为嵌套资源和用户创建测试数据时遇到问题。 I usually end up with a before(:each) that sets up the data, this is run by more than 120 of my specs. 我通常以设置数据的before(:each)结尾,它由120多个规范运行。 Let me show you: (it's not accurate, but you should get the point) 让我告诉你:(虽然不准确,但您应该明白这一点)

def setup_test_data
  @user = FactoryGirl.create(:admin_with_account)
  @account = @user.account
  3.times do |n|
    list = FactoryGirl.create(:list)
    list.items << FactoryGirl.create_list(:item, 3)
    @account.lists << list
  end  
end

before(:each){setup_test_data}

subject{List.merge(list1, list2)}
it{should have(6).items}

And here is why I fail to shorten my test data setup 这就是为什么我无法缩短测试数据设置的原因

def self.merge(lists)
  merged_list = lists.first.account.subscriber_lists.build
  name = "Merge of "
  lists.each do |list|
    name << "'#{list.name}', "
    list.items.each do |item|
      merged_list.items.build(item.dup.attributes)
    end
  end
  merged_list.name = name.chop.chop
  merged_list.save!
  merged_list.reload # I use this to filter out duplicates via validations
end

My Options: A) move some logic back into the controller, less dependency on the account, save in the controller B) stub/mock a lot more, but with nested resources + associations it's hard to do 我的选择:A)将一些逻辑移回控制器,减少对帐户的依赖,保存在控制器中B)存根/模拟更多,但使用嵌套资源+关联很难做到

C) your idea here: C)您的想法在这里:

Thanks Ray 谢谢雷

C) Create your own RSpec rake task that will first import some basic data, then use DatabaseCleaner to make sure everything runs transactionally (you will have to manually clear the DB after your custom rake tasks, because for some reason it doesn't seem to be, but with DatabaseCleaner this is a one-liner). C)创建您自己的RSpec rake任务,该任务将首先导入一些基本数据,然后使用DatabaseCleaner确保所有事务均以事务方式运行(您必须在自定义rake任务之后手动清除数据库,因为出于某种原因,它似乎并没有是的,但是使用DatabaseCleaner,这是单行的)。

I use this in a situation where I have a large pre-defined dataset that I need to test against and want it to be created once, then have tests performed transactionally against it. 我使用这种情况的情况是,我有一个很大的预定义数据集,需要对其进行测试并希望创建一次,然后对它进行事务处理测试。

If this appeals to you, let me know and I can provide more code to help you out. 如果这对您有吸引力,请告诉我,我可以提供更多代码来帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM