【问题标题】:Unexpected rspec behavior意外的 rspec 行为
【发布时间】:2016-03-02 05:19:44
【问题描述】:

学习 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 测试中,因此在尝试调用测试中的函数时为零。

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    @age 是每个 Tree 对象中的一个变量。没错,这是一个范围界定“问题”,更像是一个范围界定功能 - 您的测试没有名为 @age 的变量。

    它确实有一个名为@tree 的变量。 Tree 有一个名为 age 的属性。这应该可以,如果不行,请告诉我:

    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
    

    【讨论】:

    • 谢谢,按预期工作。我的问题是,由于该方法是在与 rspec 'expect' 相同的块中调用的,所以 Ruby 会神奇地理解我在问什么。我刚刚意识到几个月前我在不同的环境中遇到了同样的问题 - 下次我会记得的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2016-07-16
    • 2016-05-10
    相关资源
    最近更新 更多