Ruby如何在包含的模块之外使用变量

时间:2018-10-12 02:47:04

标签: ruby-on-rails ruby rspec

我正在尝试将RSpec中的代码拆分为多个文件,以使其看起来更好。当前文件如下所示。

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

现在这就是重构后的样子。

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

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

这就是Calculation.rb的样子。

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

现在的问题是,当它运行时,它会抱怨var1和var2未定义。

1 个答案:

答案 0 :(得分:1)

我相信您正在寻找RSpec的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

然后将共享的示例包括在以下任意一项中:

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

您可以通过传递一个块将上下文传递给共享示例:

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