问题
What's the best practice for Rails testing for mocking objects vs. using factory objects. Should mocking only be used when a model might go to an external source? Or do you only use factories when you're testing the actual model and using mocking for everything else.
For example if we have a sales system with customers and orders when we test the customer models do we mock the order or do we just use a factory order? Does it even make a difference?
回答1:
We've had this debate often at our web shop, and have not come to a definitive answer. Factories have the benefit of testing the interaction with the database, and we have found some problems that way that would have been missed with mocks & stubs. On the other hand, such problems are rare, and the mocks/stubs run quite a bit faster, which encourages more testing.
So we have evolved toward using mocks & stubs rather than factories in unit tests, combined with integration testing that forgoes both, and so tests functional interactions with the db that mocked & stubbed unit tests do not. This seems to strike the right balance for us.
来源:https://stackoverflow.com/questions/10471760/rails-model-testing-mocking-vs-factories