RSpec allows users to share context across tests / examples, which would reduce the number of code lines in my app by a significant amount.

On the other hand, somehow related to the question of sharing codebase between tests, one of the reasons why I'm using Factories and not Fixtures is because I don't want tests to be dependent on code stored outside the tests. Ryan Bates explains it better:

There’s a heavy dependency between the tests and the fixtures and we can cause the tests to fail just by changing the fixtures. External dependencies that are this strong aren’t a good idea and make the tests brittle.

What's best practice here, to share context across tests or to have an independent context for each test?

  • I think you are confusing terms here. RSpec allows for "shared contexts". Within those contexts, because they behave similar to ruby modules, you can define methods and even take advantage of the "let" helpers (see relishapp.com/rspec/rspec-core/v/2-14/docs/helper-methods/…). Usually when I hear people use the word "factories" in a testing context, it's really referring to a library that replaces ActiveRecord's fixtures with something else, factory_girl is one such library. Jun 9, 2013 at 2:48
  • If this question was changed to "Shared context: good or bad?" then I think I'd be able to provide an answer. Jun 9, 2013 at 2:49
  • You are right, I changed it. Jun 18, 2013 at 10:52

1 Answer 1


The factory in of itself is supposed to seem stateless, in that from the caller point of view, the factory does the same thing each and every time. So logically, the only way you could present a problem sharing a factory is if you somehow breached this contract and returned instances were somehow affected by previous calls to the factory.

In other words, a factory can and usually does perform optimizations for creating instances, but the caller can't be at all affected by this. So in the simple case in which a factory merely creates an instance and returns it would not cause you problems which you would have to worry about with a shared factory.

However, while a factory can optimize this by sharing instances, it's understood that the objects being shared are (or seemingly) stateless. If they are not and if you are lucky, you see these errors immediately, though if you're not lucky, then you receive a series of bugs in your program that may not present themselves until many months later. This is an anti-pattern and if I may add, a particularly nasty one.

So if you want to use a factory, just be sure it fits the pattern. If you're not dealing with stateless objects, just don't take any shortcuts and instantiate each object when the factory is called to create an instance and you should be fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.