RSpec之前在助手中

Nic*_*ick 2 ruby rspec ruby-on-rails helper

有可能做这样的事情吗?

module MyHelper
  before (:each) do
    allow(Class).to receive(:method).and_return(true)
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在测试中,我可以执行以下操作:

RSpec.describe 'My cool test' do
  include MyHelper
  it 'Tests a Class Method' do
    expect { Class.method }.to eq true
  end
end
Run Code Online (Sandbox Code Playgroud)

编辑:这将产生以下错误:

undefined method `before' for MyHelper:Module (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

本质上,我有一个案例,其中许多测试执行不同的操作,但是跨它们的通用模型对after_commit做出反应,最终会始终调用与API通讯的方法。我不想在全球范围内允许Class接收,:method因为有时我需要为特殊情况自己定义它...但是我不想不必重复我的allow / receive / and_return而是将其包装在一个通用帮助器中。 。

VAD*_*VAD 6

可以使用名为shared_context的功能来做你想做的事情

您可以使用这样的代码创建共享文件

共享文件.rb

shared_context "stubbing :method on Class" do
  before { allow(Class).to receive(:method).and_return(true) }
end
Run Code Online (Sandbox Code Playgroud)

然后您可以将该上下文包含在您想要的块中所需的文件中,如下所示

你的规范文件.rb

require 'rails_helper'
require 'shared_file'

RSpec.describe 'My cool test' do
  include_context "stubbing :method on Class"
  it 'Tests a Class Method' do
    expect { Class.method }.to eq true
  end
end
Run Code Online (Sandbox Code Playgroud)

对于 RSpec 来说,它比包含/扩展的模块助手更自然。可以说,这将是“RSpec 方式”。


Ste*_*fan 6

您可以创建一个通过元数据触发挂钩,例如:type => :api

RSpec.configure do |c|
  c.before(:each, :type => :api) do
    allow(Class).to receive(:method).and_return(true)
  end
end
Run Code Online (Sandbox Code Playgroud)

在您的规格中:

RSpec.describe 'My cool test', :type => :api do
  it 'Tests a Class Method' do
    expect { Class.method }.to eq true
  end
end
Run Code Online (Sandbox Code Playgroud)

您还可以传递:type => :api到各个it块。