加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 意外的rspec行为

发布时间:2020-12-17 03:18:36 所属栏目:百科 来源:网络整理
导读:学习Rspec,只使用 Ruby,而不是Rails.我有一个脚本,从命令行按预期工作,但我无法通过测试. 相关代码: class Tree attr_accessor :height,:age,:apples,:alive def initialize @height = 2 @age = 0 @apples = false @alive = true end def age! @age += 1 en
学习Rspec,只使用 Ruby,而不是Rails.我有一个脚本,从命令行按预期工作,但我无法通过测试.

相关代码:

class Tree    
  attr_accessor :height,:age,:apples,:alive

  def initialize
    @height = 2
    @age = 0
    @apples = false
    @alive = true
  end      

  def age!
    @age += 1
  end

规范:

describe "Tree" do

  before :each do
    @tree = Tree.new
  end

  describe "#age!" do
    it "ages the tree object one year per call" do
      10.times { @tree.age! }
      expect(@age).to eq(10)
    end
  end
end

而错误:

1) Tree #age! ages the tree object one year per call
     Failure/Error: expect(@age).to eq(10)

       expected: 10
            got: nil

       (compared using ==)

我认为这是所有相关的代码,如果我在发布的代码中遗漏了某些内容,请告诉我.从我可以看出错误来自rspec中的范围,并且@age变量没有以我认为它应该的方式传递到rspec测试,因此在尝试调用测试中的函数时是nil.

解决方法

@age是每个Tree对象中的变量.你是对的,这是一个范围’问题’,更像是一个范围界定功能 – 你的测试没有名为@age的变量.

它具有的是一个名为@tree的变量.那棵树有一个叫做年龄的房产.这应该工作,如果不是,请告诉我:

describe "Tree" do

  before :each do
    @tree = Tree.new
  end

  describe "#age!" do
    it "ages the tree object one year per call" do
      10.times { @tree.age! }
      expect(@tree.age).to eq(10) # <-- Change @age to @tree.age
    end
  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读