Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between mock, stub, and factory girl?

I'm pretty new to rspec and the whole TDD methodology. Can someone please explain the difference between mock and stub. When do we use them and when do we use Factory Girl to create objects in test cases?

like image 329
trivektor Avatar asked Sep 07 '11 21:09

trivektor


People also ask

What is a stub mock?

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 does Factory Girl do?

Factory Girl provides a well-developed ruby DSL syntax for defining factories like user, post or any other object—not only Active Record objects. “Plain” Ruby classes are perfectly fine. You start by setting up a define block in your factories. rb file.

What is the difference between stub and fake?

There are different test doubles with different purposes—fakes, mocks, and stubs. Fakes are objects that have working implementations. On the other hand, mocks are objects that have predefined behavior. Lastly, stubs are objects that return predefined values.

What is a factory fixture?

A Fixture is "the fixed state used as a baseline for running tests in software testing" A Factory is "an object for creating other objects"


1 Answers

You could think of a mock (or double) as a fake object. When you're testing and need to work with an object that isn't easily usable inside your test, you could use a mock as an approximation for how you expect that object to behave and work around it. Stubs can be used in a similar manner but on an individual method on an object.

Here's a rather contrived example of using a lot of both:

class Client   def connect_to_server     if Server.connect.status == 'bad'       show_an_error     else       do_something_else     end   end   def do_something_else; end   def show_an_error; end end  context "failure" do   it "displays an error" do     bad_network_response = double("A bad response from some service", :status => 'bad')     Server.should_receive(:connect).and_return(bad_network_response)      client = Client.new     client.should_receive(:show_an_error)     client.connect_to_server   end end 

You can imagine that using a lot of mocks or stubbing is a bad idea; this is basically masking out parts of your code in your test but, it's an easy solution for some difficult/rare testing scenarios.

Factory Girl is useful for generating data for tests. You would use factories as recipes for creating instances for your models, you might need to test something involving a lot of test data and this would be a situation where using fixtures won't work and creating complicated objects explicitly can be tedious.

like image 199
jdeseno Avatar answered Oct 19 '22 08:10

jdeseno