dee
dee

Reputation: 1898

How do I use Rspec shared_examples across different files?

I want to reuse this shared_examples block across different spec files. I want to extract it into a separate file, and pass in the object so it's not always user. Both things I tried failed, is it possible?

describe User  do
  before  { @user = build_stubbed(:user) }
  subject { @user }

  shared_examples 'a required value' do |key| # trivial example, I know
    it "can't be nil" do
      @user.send("#{key}=", nil)
      @user.should_not be_valid
    end
  end

  describe 'name'
    it_behaves_like 'a required value', :name
  end
end

Upvotes: 4

Views: 3760

Answers (1)

Aaron K
Aaron K

Reputation: 6961

Just require the other file. shared_examples work at the top level, so once defined they are always available; so be careful of naming conflicts.

A lot of RSpec users will put the shared example in spec/support/shared_examples/FILENAME.rb. Then in spec/spec_helper.rb have:

Dir["./spec/support/**/*.rb"].sort.each {|f| require f}

Or on Rails projects

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}

That is listed in the 'CONVENTIONS' section of the shared example docs.

Upvotes: 8

Related Questions