I'm new to RSpec and I'm just wondering how to reuse a context across several actions in a controller. Specifically, I have code like this:
describe "GET index" do
context "when authorized" do
...
end
context "when unauthorized" do
it "denys access"
end
end
describe "GET show" do
context "when authorized" do
...
end
context "when unauthorized" do
it "denys access"
end
end
...
And I'd like to DRY it up a bit. The unauthorized context is the same on every action, how can I reuse it?
Shared examples are your friend:
Create a new file, something like spec/shared/unauthorized.rb
and include it in your spec_helper
then format it like this:
shared_examples_for "unauthorized" do
context "when unauthorized" do
it "denys access"
end
end
Then in your specs:
include_examples "unauthorized"
Do that in each describe block and you should be golden.