Skip to content

Instantly share code, notes, and snippets.

@chrmod
Last active December 27, 2015 09:19
Show Gist options
  • Save chrmod/7302952 to your computer and use it in GitHub Desktop.
Save chrmod/7302952 to your computer and use it in GitHub Desktop.
rspec mock helper

rSpec #mock DSL helper

This Gist describe a concept of little helper method to speed up mocking of object methods using rSpec. It addresses a simplification of common pattern used while creating mock:

describe "some behaviour" do

  let(:some_important_data) { "some text, array, hash or maybe an object" } 

  before do
    allow(InterestingClass).to receive(:some_important_data).and_return(some_important_data)
  end

  it do 
    expect(InterestingClass).to receive(:some_important_data)
    subject
  end

  it do
    expect(subject).to eql(some_important_data+"some other data")
  end 

end

Simplified version may look like this:

describe "some behaviour" do

  mock(InterestingClass, :some_important_data) { "some text, array, hash or maybe an object" }

  it do 
    expect(InterestingClass).to receive(:some_important_data)
    subject
  end

  it do
    expect(subject).to eql(some_important_data+"some other data")
  end 

end

or simpler:

describe "some behaviour" do

  # Note the `!` in `#mock!`
  mock!(InteresingClass, :some_important_data) { "some text, array, hash or maybe an object" }

  it do
    expect(subject).to eql(some_important_data+"some other data")
  end 

end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment