Reputation: 8372
Suppose you have a shopping site that sells widgets. However, the inventory of each widget is limited, so it's important to keep the "widget.number_still_available" number up to date.
I'd like to write an rspec test along the lines of
it "always displays the correct number still available" do
# Assume there is a before method that sets up a widget with 5 available
widget.number_still_available.should == 5
# User "[email protected]" purchases 2 widgets
widget.number_still_available.should == 3
# User "[email protected]" purchases 1 widget
widget.number_still_available.shhould == 2
# User "[email protected]" cancels purchase of 1 widget
widget.number_still_available.should == 4
end
I'd like to be able to write testing-only methods that performs the "purchasing" and "canceling" methods. These actions don't correspond to any "real" methods in my models for a variety of reasons (most significantly there is a decoupled back-end system in PHP that performs part of the purchasing and canceling actions).
Where is the correct place to put this code when using RSpec? In cucumber, I could write a couple of steps - but I'm not sure what the correct equivalent is for RSpec.
Upvotes: 24
Views: 8332
Reputation: 107728
I would suggest making a new file in spec/support
called purchase_helpers.rb
and put this content in it:
module PurchaseHelpers
def purchase_widgets(user, count=1)
# Code goes here
end
def cancel_purchase(user, count=1)
# Code goes here
end
end
RSpec.configure do |c|
c.include PurchaseHelpers
end
The benefit of doing this rather than chucking it into spec/spec_helper.rb
is that it is not crowding up that file with a lot of unrelated-to-the-setup-of-RSpec code. Separating things out is the better way to do things.
Upvotes: 47
Reputation: 22751
You can drop a monkeypatch into spec_helper.rb, or directly at the top of the spec file if it's only used for that one file.
It would be more clear and safe to make helper methods which use existing class methods, instead of monkeypatching the classes.
Upvotes: 2