Search code examples
rspeccode-reuse

Code reuse in different rspec contexts


I am trying to reuse some common code in a rails controller spec. I have different contexts for admin users and regular users. However, much of the behavior is the same for particular actions, so I tried pulling that common behavior out into a helper function:

describe SomeController do
    def common_get_new
       # common stuff
    end 

    context "regular users" do
        describe "GET new" do
            common_get_new
        end
    end

    context "admin users" do
        describe "GET new" do
            common_get_new
        end
    end
end

This gives me the error:

undefined local variable or method `common_get_new'

What am I doing wrong?


Solution

  • Have you tried using Shared Examples?

    describe SomeController do
      shared_examples_for "common_get_new" do
        # common stuff
      end 
    
      context "regular users" do
        describe "GET new" do
          it_should_behave_like "common_get_new"
        end
      end
    
      context "admin users" do
        describe "GET new" do
          it_should_behave_like "common_get_new"
        end
      end
    end
    

    Depending on what is in your common_get_new method in your question, in order to simply get rid of your error, you could put the method in spec/support/utilities.rb, or do as @Chris Heald suggested and define the method at the top of the file.