繁体   English   中英

Ruby / Rails测试-访问范围之外的变量?

[英]Ruby/Rails testing - access variable outside of scope?

我想使用rspec的RoR对单元方法进行单元测试,并具有如下方法:

def create_record(obj, params)
    begin
      obj.add_attributes(params)
      result = obj.save
    rescue
      MyMailer.failed_upload(@other_var, obj.api_class_name, params).deliver_now
    end
end

从不直接调用create_record ,而是通过另一种适当填充@other_var方法来调用。

我应该如何测试代码以确保正确调用MyMailer? 我应该将@other_var传递给该方法,而不是依靠它在其他地方填充(aka:这是代码味道吗?)? 谢谢!

在Ruby中,您可以使用Object#instance_variable_set设置任何实例变量。

RSpec.describe Thing do 
  describe "#create_record" do
    let(:thing) do
      t = Thing.new
      t.instance_variable_set(:@other_var, "foo")
      t
    end
    # ...
  end
end 

这完全避开了任何封装,这意味着可以将instance_variable_set的使用视为代码气味。

另一种选择是使用RSpecs的模拟和存根工具,但是存根实际的测试对象也是一种代码味道。

您可以通过将依赖项作为参数传递或通过构造函数注入来避免这种情况:

class Thing
  attr_accessor :other_var

  def initialize(other_var: nil)
     @other_var = other_var
  end

  def create_record(obj, attributes)
     # ...
  end
end

一个很好的模式是服务对象

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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