Question

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?

Was it helpful?

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.

OTHER TIPS

Try rearranging your contexts so that deeper contexts can share the same setup code:

describe SomeController do
  describe "GET new" do
    before do
       # common stuff
    end

    context "regular users" do
    end

    context "admin users" do
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top