Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby如何在包含的模块之外使用变量_Ruby On Rails_Ruby_Rspec - Fatal编程技术网

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

Ruby on rails Ruby如何在包含的模块之外使用变量,ruby-on-rails,ruby,rspec,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

我正在尝试将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没有定义。

我相信您正在寻找RSpec的:

然后,您可以将共享示例包括在以下任意示例中:

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

您应该注意到,
let
不是一个Ruby语法的东西,而是一个RSpec的东西,它使用元编程来创建记忆化的助手。因此,仅仅通过查看语言,您无法真正理解let如何在不同的上下文中工作。我不认为你可以像共享上下文那样,只用一个简单的模块就可以做到这一点。
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