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
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? Minitest is a testing tool for Ruby that provides a complete suite of testing facilities. It also supports behaviour-driven development, mocking and benchmarking.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With