Ruby 试图在rspec中使用“实例变量集”时出现未定义的局部变量或方法错误
我有一节这样的课Ruby 试图在rspec中使用“实例变量集”时出现未定义的局部变量或方法错误,ruby,rspec,Ruby,Rspec,我有一节这样的课 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 这是它的规范文件 需要相对“foo” describe Foo do let(:
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
这是它的规范文件
需要相对“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)
和spec文件,以测试在连接失败30次时调用send\u error
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
我不知道你想做什么,但我怀疑这不是正确的做法
然而,您眼前的问题是您不在测试的上下文中,因此
foo
是未定义的。你想把你的foo.instance\u variable\u set
包装在一个测试结构中-要么是it
或者指定
块,要么是前面的:每个
,或者类似的东西。我现在可以使用instance\u variable\u set
,谢谢!如果您能告诉我在这种情况下应该如何测试,我将不胜感激。我在我的问题中添加了更多的代码。我不会在模型中使用实例变量-我会用attr\u访问器来结束它。在测试中,我只需在对象上存根方法error\u count
,以返回您想要的值。
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