The rspec controller specification on a controller with names discovers a global controller with the same name

I have a strange problem when creating a controller specification for a controller with a namespace when there is also a global controller with the same name.

The names of the HomeController and Backend::HomeController controllers.

Please note that I have not yet created the app/controllers/backend/home_controller.rb , only the global controller app/controllers/home_controller.rb

Therefore, I expect the test to explode with errors, but it is not. He passes, all green and happy.

My specs look like

 #spec/controllers/backend/home_controller_spec.rb require 'rails_helper' RSpec.describe Backend::HomeController, type: :controller do before do user = FactoryGirl.create(:user) allow(controller).to receive(:authenticate_user!).and_return(true) allow(controller).to receive(:current_user).and_return(user) end describe "GET #index" do it "returns http success" do get :index expect(response).to have_http_status(:success) end end end 

However, if I change the name in my global HomeController to something else, such as NotMyHomeController , the test will NotMyHomeController with the error saying

 Unable to autoload constant HomeController, expected app/controllers/home_controller.rb to define it 

Which makes me suspect that Rspec is not worried about the "Backend" part in the Rspec.describe function.

Am I doing something wrong or am I missing some other vital part? IMHO, this specification should not pass (rephrase Gandalf).

I am using Rails 4.2.6, Rspec-Rails 3.4.2

Update

As Max pointed out, this is probably not an Rspec problem, but instead something with Rails startup.

However, I tried to just type

 Backend::HomeController 

In the Rails console, but there I get the expected error

 NameError: uninitialized constant Backend::HomeController 

And according to the Rails manual , both for the console and for autoload of the test suite. However, I think I'm on the right track here.

+5
source share
1 answer

I had the same problem before - you can read about the whole here:

Object.const_get and Rails - disable parent module names

but the meat of the answer comes from this answer from the Apneadiving user:

Keep in mind that there are flawed cases in Rails development mode. To get speed, a strict minimum is loaded. Rails then searches for class definitions when necessary.

But this sometimes is not suitable for an example with a long time, when you already said ::User already loaded, and then look for ::Admin::User . Rails will not look for him, he will think that ::User doing the trick.

This can be solved using the require_dependency statements in your code.

+1
source

Source: https://habr.com/ru/post/1246103/


All Articles