Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Fixtures vs. Mocks

I'm developing a Rails app, and I was just talking with my colleague that we have a mix of fixtures and mocks in our tests, which we're doing using cucumber and Rspec. The question would be: when should each one be used?

like image 966
Thiago Avatar asked May 26 '10 22:05

Thiago


People also ask

What is a difference between a mock and a stub?

Stub: a dummy piece of code that lets the test run, but you don't care what happens to it. Substitutes for real working code. Mock: a dummy piece of code that you verify is called correctly as part of the test. Substitutes for real working code.

What are fixtures in rails?

Fixtures are data that you can feed into your unit testing. They are automatically created whenever rails generates the corresponding tests for your controllers and models. They are only used for your tests and cannot actually be accessed when running the application.

What is the benefit of using factories over fixtures?

It has a benefit of clarity and low overhead. Like I said above, I've definitely used factories more than fixtures. My main reason is that when I use factories, the place where I specify the test data and the place where I use the test data are close to each other. With fixtures, on the other hand, the setup is hidden.

What are RSpec fixtures?

Fixtures allow you to define a large set of sample data ahead of time and store them as YAML files inside your spec directory, inside another directory called fixtures. When you're test sweep first starts up RSpec will use those fixture files to prepopulate your database tables.


1 Answers

I would use a mock object when using the real object is impracticable/not necessary. Lets say for example you need to call some remote API such as an address finder via zip code. You would probably want to mock the object so the calls on it aren't actually made each time you run your tests. There are other reasons too such as improving speed, asking for data that changes where you need an exact response or perhaps it doesn't exist yet. It allows you to test things in isolation as you can determine that when you call these methods on this mock object you will get this back and you don't actually need to run the code as for this test it's not important.

If you use fixtures you will have a real object and the methods etc will be called and their code run, unless of course you stub the methods out, which is something for another question.

Hope that helps a little. There is a good peepcode (http://peepcode.com/products/rspec-mocks-and-models) on mocking and stubbing, maybe check it out.

like image 53
tsdbrown Avatar answered Jan 01 '23 21:01

tsdbrown