Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 986
dee Avatar asked Oct 14 '25 09:10

dee


1 Answers

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.

like image 138
Aaron K Avatar answered Oct 18 '25 03:10

Aaron K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!