Domanda

I've got a really ugly controller spec that looks like this:

describe "GET index" do
  context "when authorized" do
    before(:each) do
      sign_in @user
    end

    ...
  end

  include_examples "when unauthorized"
end

describe "GET show" do
  context "when authorized" do
    before(:each) do
      sign_in @user
    end

    ...
  end

  include_examples "when unauthorized"
end

...

Is there any way to move the before filter and shared example out into some kind of common feature of each action? If not, is there any way to DRY this up at all?

È stato utile?

Soluzione

Yes you can. An example from:https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples

require "set"

shared_examples "a collection object" do
  describe "<<" do
    it "adds objects to the end of the collection" do
      collection << 1
      collection << 2
      expect(collection.to_a).to match_array([1, 2])
    end
  end
end

describe Array do
  it_behaves_like "a collection object" do
    let(:collection) { Array.new }
  end
end

describe Set do
  it_behaves_like "a collection object" do
    let(:collection) { Set.new }
  end
end

I should stress that every test should only test one thing so be careful how you write it. You can also move shared content to a separate file which the link above shows as well under the shared content tab.

Remember that you want your tests to be readable. For small bits of code like the before filter and signing in I leave in. It may not be DRY, but for me it is easier to read the test straight through rather than referring to separate examples or files. If you have a large test that you are doing multiple times it would be easier to move it out to a separate example or file.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top