Skip to content

Instantly share code, notes, and snippets.

@mikepack
Created August 3, 2012 03:18
Show Gist options
  • Save mikepack/3244024 to your computer and use it in GitHub Desktop.
Save mikepack/3244024 to your computer and use it in GitHub Desktop.
Testing blocks

How do you test this?

I want to test that something receives #var from inside the block.

I realize this might be a code smell.

something = Struct.new(:var).new
some_method do
  something.var
end

I want to test that #var was sent to something. In other words, something.should_receive(:var).

@myronmarston
Copy link

It's not clear to me what you're asking--on the surface, it sounds like something.should_receive(:var) would work, but it's clear there's more going on here..

@mikepack
Copy link
Author

mikepack commented Aug 3, 2012

Sorry for not being clear. I want to test that it's happening inside the block.

@myronmarston
Copy link

Sorry for not being clear. I want to test that it's happening inside the block.

Ah, that makes more sense. What is the observable difference in the behavior for something.var to be called in the block vs. outside of it? Is there a way to test that w/o explicitly specifying the relationship between the block and the call to var?

Anyhow, if you still want to test this directly, here's one idea. If there's some observable state change for the duration of the block, then you can pass a block to should_receive to test this. For example, let's use Dir.chdir in place of some_method...then you could test it like so:

it 'does something within another directory' do
  expect(Dir.pwd).not_to eq("other/dir")

  something = Struct.new(:var).new
  something.should_receive(:var) do
    expect(Dir.pwd).to eq("other/dir")
  end

  Dir.chdir("other/dir") do
    something.var
  end

  expect(Dir.pwd).not_to eq("other/dir")
 end

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