【问题标题】:undefined local variable or method error when trying to use `instance_variable_set` in rspec尝试在 rspec 中使用“instance_variable_set”时出现未定义的局部变量或方法错误
【发布时间】:2014-04-09 14:40:31
【问题描述】:

我有这样的课

require 'net/http'
class Foo
  def initialize
    @error_count = 0
  end
  def run
    result = Net::HTTP.start("google.com")
    @error_count = 0 if result
  rescue
    @error_count += 1
  end
end

这是它的规范文件。

require_relative 'foo'

describe Foo do
  let(:foo){ Foo.new}
  describe "#run" do
    context "when fails 30 times" do
      foo.instance_variable_set(:@error_count, 30)
    end
  end
end

然后运行rspec foo_spec.rb,然后失败并出现此错误。

foo_spec.rb:7:in `block (3 levels) in <top (required)>': undefined local variable or method `foo' for #<Class:0x007fc37410c400> (NameError)

我应该如何在 rspec 中调用instance_variable_set 方法?

编辑

如果30次失败,我想调用send_error方法。

require 'net/http'
class Foo
  def initialize
    @error_count = 0
  end
  def run
    result = Net::HTTP.start("google.com")
    @error_count = 0 if result
  rescue
    @error_count += 1
    send_error if @error_count >= 30
  end
  def send_error
  end
end

以及用于测试send_error 在连接失败 30 次时被调用的规范文件。

require_relative 'foo'

describe Foo do
  let(:foo){ Foo.new}
  describe "#run" do
    context "when fails 30 times" do
      it "should send error" do
        foo.instance_variable_set(:@error_count, 30)
        expect(foo).to receive(:send_error)
      end
    end
  end
end

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    我不知道你想做什么,但我怀疑这不是做事的正确方法。

    但是,您的直接问题是您不在测试的上下文中,因此 foo 未定义。您想将您的 foo.instance_variable_set 包装在一个测试构造中 - itspecify 块,或 before :each,或类似的东西。

    【讨论】:

    • 我现在可以使用instance_variable_set,谢谢!如果您告诉我在这种情况下我应该如何测试,我将不胜感激。我在我的问题中添加了更多代码。
    • 我不会在你的模型中使用实例变量——我会用attr_accessor 来结束它。在测试中,我会简单地在对象上存根方法error_count 以返回您想要的值。
    猜你喜欢
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多