TrongBang
TrongBang

Reputation: 967

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.

Upvotes: 0

Views: 46

Answers (1)

max
max

Reputation: 102134

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

Upvotes: 1

Related Questions