Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a function which takes a block with rspec

I have a function, which accepts a block, opens a file, yields and returns:

def start &block
    .....do some stuff
    File.open("filename", "w") do |f|
        f.write("something")
        ....do some more stuff
        yield
    end
end

I am trying to write a test for it using rspec. How do I stub File.open so that it passed an object f (supplied by me) to the block instead of trying to open an actual file? Something like:

it "should test something" do
    myobject = double("File", {'write' => true})
    File.should_receive(:open).with(&blk) do |myobject|
        f.should_receive(:write)
        blk.should_receive(:yield) (or somethig like that)
    end
end
like image 220
constantine1 Avatar asked Feb 19 '13 10:02

constantine1


People also ask

How do I run a specific test in RSpec?

To run a single Rspec test file, you can do: rspec spec/models/your_spec. rb to run the tests in the your_spec. rb file.

What is Minitest?

What is Minitest? Minitest is a testing tool for Ruby that provides a complete suite of testing facilities. It also supports behaviour-driven development, mocking and benchmarking.

What is mocking in RSpec?

Mocking is the practice of using fake objects to mimic the behaviour of real application components. Since mock objects simulate the behaviour of the original components, they can be used during testing of an isolated application code to handle its interaction with other parts of the application.

What type of testing is RSpec?

RSpec is a testing tool for Ruby, created for behavior-driven development (BDD). It is the most frequently used testing library for Ruby in production applications. Even though it has a very rich and powerful DSL (domain-specific language), at its core it is a simple tool which you can start using rather quickly.


1 Answers

I think what you're looking for are yield matchers, i.e:

it "should test something" do
  # just an example
  expect { |b| my_object.start(&b) }.to yield_with_no_args
end
like image 93
Amir Avatar answered Oct 22 '22 01:10

Amir