How can I have faster tests and still use Factory Girl?
I really like using Factory Girl to setup my tests. I can build chains of associations in a single line. For example:
Factory.create(:manuscript)
Automatically creates a journal, a journal owner, a manuscript author, etc. It allows me to to keep my setup blocks really si开发者_Python百科mple, and that's fantastic.
However, there's a cost of course. Creating several objects in the background means my unit tests are sometimes as long as 0.8 seconds. That's fine when your app is small, but now I've got a few hundred tests and my specs take over a minute to run (not including the time it takes for the app to spin up). It's starting to feel painful.
I'm not especially interested in anything too drastic, like mocking everything. At least while my app is relatively small, I'd like to maintain my factory girl abstractions. I just want to figure out a way to make them work a bit faster.
Any suggestions?
If you're testing object behavior and don't need to actually save them to a database, you can use Factory.build(:model)
. It basically instantiates the object and it's associations, but does not write it to the DB. This will be much faster than creating and storing all those objects. If you still want to write some or most objects to the DB, you can setup an SQlite memory test database. Here's an example
Not sure there's a good solution to this problem. As Beerlington suggested, you can save some time using Factory.build
rather than Factory.create
. But even that's not nearly as fast as testing a plain old ruby objects. The fact, it seems, is that factory girl is not a good choice if you're very concerned with speed.
That said, I was able to make some fairly significant speed improvements by reading through my entire suite and making liberal use of the rspec-set gem. This allows you to run your setup once -- and only once -- for the entire group of tests. It's similar to using before(:all)
except that it takes advantage of transactions to reset the state of objects between each spec.
精彩评论