Say I have an instance method that does many different things that I need to test, something like store#process_order. I’d like to test that it sends an email to the customer, adds an entry in the orders table, charges a credit card, etc. What’s the best way to set this up in rspec? Currently, I’m using rspec and factory girl I do something like this:
describe Store do
describe "#process_order" do
before do
@store = Factory(:store)
@order = Factory(:order)
# call the process method
@store.process_order(@order)
end
it 'sends customer an email' do
...
end
it 'inserts order to db' do
...
end
it 'charges credit card' do
...
end
end
end
But it feels really tedious. Is this really the right way to write a spec for a method that I need to make sure does several different things?
Note: I’m not interested in answers about whether or not this is good design. It’s just an example I made up to help w/ my question – how to write these types of specs.
I think what you are doing is fine and I think it’s the way rspec is intended to be used. Every statement (specification) about your app gets its own block.
You might consider using
before (:all) doso that the order only has to get processed once but this can introduce dependencies on the order the specs are run.You could combine all the code inside
describe "#process_order"into one bigitblock if you wanted to, but then it would be less readable and rspec would give you less useful error messages when a spec fails. Go head and addraiseto one of your tests and see what a nice error message you can get from rspec if you do it the way you are currently doing it.