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. 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
C) your idea here:
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).
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.