Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you factor out common "before(:each)" calls in RSpec so that multiple specs can use them?

I'd like to factor this bunch of code so that all of my controller tests (well, almost all of them) use this before(:each) block:

before(:each) do
  @user = User.new
  controller.stub(:authenticate_user!)
  controller.stub(:current_user).and_return(@user)
  controller.stub(:add_secure_model_data)
end

Is there any way to do that? I don't want to include it in all controllers... because there are a few that don't need this. By basically, every controller that extends from SecureController will need this before(:each) block.

Is there any nice way to do that?

Thanks

like image 647
Fire Emblem Avatar asked May 25 '11 21:05

Fire Emblem


2 Answers

http://relishapp.com/rspec/rspec-core/dir/example-groups/shared-context

shared_context "controller stuff" do
  before(:each) { ... }
end

describe SomeController do
  include_context "controller stuff"
  ...
end
like image 112
David Chelimsky Avatar answered Sep 20 '22 14:09

David Chelimsky


So put the block into SecureController.

If there are specific children of SecureController that don't want this functionality, you could make another intermediate superclass, or wrap the method call with a conditional you control.

like image 36
DigitalRoss Avatar answered Sep 21 '22 14:09

DigitalRoss