Skip to content

Instantly share code, notes, and snippets.

@andhapp
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save andhapp/9088908 to your computer and use it in GitHub Desktop.

Select an option

Save andhapp/9088908 to your computer and use it in GitHub Desktop.

Revisions

  1. andhapp revised this gist Feb 20, 2014. 1 changed file with 61 additions and 2 deletions.
    63 changes: 61 additions & 2 deletions stub v should_receive
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,63 @@
    # stub
    ## stub v should_receive

    ## This is just a simple example to show uses of stub, and should_receive. Imagine you have the following code:

    # should_receive
    # topic.rb
    class Topic < ActiveRecord::Base
    has_many :stories

    def add_story(story)
    unless exists? story
    update_stories_association(story)
    end
    end

    def exists?(story)
    .... # some code to test if the story exists
    end

    def update_stories_association
    .... # some code to update story association
    end
    end

    # story.rb
    class Story < ActiveRecord::Base
    belongs_to :topic
    end

    # topic_spec.rb
    describe Topic do
    # Here the intent is to just test the add_story is behaving in the way it does
    # and in order to test both the case when story exists and story doesn't exist
    # we will stub (fake) the exists? method to return what we want it to return
    describe '#add_story' do
    it 'does not add already associated story' do
    topic = Topic.new
    story = Story.new

    # this tests the case when the story exists, the exists? method could go and talk to database
    # but we don't care about it whilst testing add_story, we just ensure that the add_story behaves
    # as expected for when the topic exits
    topic.stub(:exists? => true)

    topic.add_story(story)

    # should_receive on the other hand will test what you expect to happen
    topic.should_receive(:update_stories_association).never
    end

    it 'adds a new story' do
    topic = Topic.new
    story = Story.new

    topic.stub(:exists? => false)

    topic.add_story(story)

    # should_receive on the other hand will test what you expect to happen
    topic.should_receive(:update_stories_association).once
    end

    end
    end
  2. andhapp created this gist Feb 19, 2014.
    4 changes: 4 additions & 0 deletions stub v should_receive
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,4 @@
    # stub


    # should_receive