Friday, January 11, 2013

Mocks, Stubs, and Rspec

I have been reading the stats behind learning and how blogging after absorbing information is one of the best ways to solidify information that you have been processing. I will most likely not be able to do this during DBC, but the time being I will try to write short bite-sized blogs about the lessons that I have learned in between the weekly posts so I can take the most important information that I have learned from the day and put it on paper (or in this case, the web). So here it is:

I have been reading Eloquent Ruby by Russ Olsen and the information that I have went over today included Rspec testing, Mocks, and Stubs.

Mocks Vs. Stubs: The most basic overview of the difference between mocks and stubs is that stubs return a canned answer like in their example of having a printer that is available. Mocks on the other hand are stubs that are capable of knowing what methods should be called as well as with what arguments.

Their names really do them justice. Think of a stub like stubbing out a pipe in a building to where gas goes and knows that a pipe is there, but is confined to the simple data it has been given and cannot know more actions than that the pipe is available for gas to travel to. The mock on the other hand would be like running a gas line in a loop through a room instead of through the whole house to get the feel of running gas through the pipes around, but not with all the complexity and possibility for failure as mapping out the entire houses gas lines and the twists and turns involved.

Rspec: I have dealt with Rspec before and at it's core is Ruby's most popular testing Framework. It is very high level and is read more or less like with english syntax. Now less about that and more helpful tidbits:
  • Spec_helper: Have to write require 'spec_helper' in order for the framework to work properly with gems that are installed such as simplecov (code coverage), rubygems, spork, etc..
  • Testing Classes: To start a test you want to specify what class you are testing. Write describe Micropost do to test the Micropost class.
  • Specific Test: When starting a specific test you write it 'you can write whatever you want to test within these apostrophes' do. This is followed by the test and then end. example:
describe Micropost do
    describe "when user_id is not present" do
    before { @micropost.user_id = nil }
    it { should_not be_valid }
  end

  • Rspec Files: Rspec files should be saved as class_spec.rb
That's it for now, have to catch the bus to work. I'm excited for a month of pure focus with nothing but studying before this journey begins on March 11th. Upwards and onwards...


No comments:

Post a Comment