Reputation: 196
I want to properly use module
files in a spec/support/
rspec directory for a typical Ruby on Rails project.
# spec/support/page_objects/foo/bar.rb
module Foo
module Bar
def hello
"hello world"
end
end
end
# spec/support/page_objects/foo/foo_bar.rb
class FooBar
include Foo::Bar
end
# spec/system/foo_bars/create_spec.rb
RSpec.describe "Create FooBar", type: :system do
it "returns hello world"
expect(FooBar.new.hello).to eq "hello world"
end
end
I would expect rspec spec/foo_bars/create_spec.rb
to pass, however I am receiving uninitialized constant Foo::Bar
.
The only way I can get it working is to require the module in the class file.
# spec/support/page_objects/foo/foo_bar.rb
require_relative("bar")
class FooBar
include Foo::Bar
end
Is there a way to properly use module
files in spec/support
to prevent having to explicitly call require
?
Upvotes: 0
Views: 1122
Reputation: 164829
Nothing in spec
is autoloaded by default.
Typically one adds a line to load spec/support files in spec/rails_helper.rb
Dir[Rails.root.join('spec/support/**/*.rb')].sort.each { |f| require f }
Note that this will add load time to all test runs regardless of whether they use your support files. This is fine for general use support files, but not such a good idea for support files specific to a single class. Those test classes will pollute every test.
Instead, consider writing them as a shared context and including as needed. Put them in a shared_context directory. You can also load all shared contexts and examples.
Dir[Rails.root.join('spec/**/shared*/*.rb')].sort.each { |f| require f }
Note that spec/support/page_objects/foo/foo_bar.rb would normally be for Foo::FooBar. FooBar should go into spec/support/page_objects/foo_bar.rb. This will have no material effect on your code, but it's good to have naming consistent with Rails standards.
Upvotes: 1