简体   繁体   中英

Ruby how to use variables outside of included modules

I'm trying to split my code in RSpec into multiple files so it looks nicer. The current file looks like this.

require 'rails_helper'

RSpec.describe Api::MyController do
   let(:var1) {}
   let(:var2) {}
   it 'should calculate some value' do
      expect(var1 + var2).to eq('some value')
   end
end

Now this is how it looks after refactoring.

require 'rails_helper'
require_relative './mycontroller/calculation'

RSpec.describe Api::MyController do
   let(:var1) {}
   let(:var2) {}
   include Api::MyController::Calculation
end

And this is how calculation.rb looks like.

module Api::MyController::Calculation
   it 'should calculate some value' do
      expect(var1 + var2).to eq('some value')
   end
end

The problem now is that when it runs, it complains var1 and var2 is not defined.

I believe you are looking for RSpec's shared examples :

# spec/support/shared_examples/a_calculator.rb
RSpec.shared_examples "a calculator" do
  it 'should calculate some value' do
    expect(x+y).to eq(result)
  end
end

You then include the shared example with any of:

include_examples "name"      # include the examples in the current context
it_behaves_like "name"       # include the examples in a nested context
it_should_behave_like "name" # include the examples in a nested context
matching metadata            # include the examples in the current context

You can pass context to the shared example by passing a block:

require 'rails_helper'
require 'support/shared_examples/a_calculator'
RSpec.describe Api::MyController do
  it_should_behave_like "a calculator" do
    let(:x){ 1 }
    let(:y){ 2 } 
    let(:result){ 3 }  
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM