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
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.