rspec / rspec-metagem

RSpec meta-gem that depends on the other components
https://rspec.info
MIT License
2.86k stars 235 forks source link

Not able to access class methods in spec even after including the module #34

Closed akash90khandelwal closed 5 years ago

akash90khandelwal commented 5 years ago

I am trying to access a class method in spec by calling it through ClassName.method_name. I have included the module of the class in spec under RSpec.configure block but still I am not able to access the method. Please refer below spec file and class file spec file

require './lib/pages/OCBC/open_account.rb'

RSpec.configure do |configure|
 configure.include OCBC
end

describe 'Test' do
 it "tests the module" do
  OpenAccount.name
 end
end

Class file

module OCBC
 class OpenAccount
  def self.name
   puts 'Akash'
  end
end

Error

NameError: uninitialized constant OpenAccount

However, when I am including module outside RSpec.configure block(as shown below), I am able to access the class method

require './lib/pages/OCBC/open_account.rb'

include OCBC

describe 'Test' do
 it "tests the module" do
  OpenAccount.name
 end
end
JonRowe commented 5 years ago

👋 This is a lexical scoping issue within Ruby, we utilise instance_exec to execute your example code within the context of the example group, so Ruby is not considering OpenAccount as a part of OCBC but of the top level. This explains why it works when you include it into main.

The work around here is to wrap your spec within the module.

module OCBC
  RSpec.describe 'Test' do
     it "tests the module" do
      OpenAccount.name
    end
  end
end