gpt4 book ai didi

ruby - 第一次在 ruby​​ 中使用 rspec 进行单元测试

转载 作者:太空宇宙 更新时间:2023-11-03 17:10:24 25 4
gpt4 key购买 nike

我只是想了解单元测试背后的基础知识。我在一个名为 Player.rb 的文件中编写了一个 Player 类。这是代码:

Class Player

attr_reader :health
attr_accessor :name

def initialize(name, health=100)
@name = name.capitalize
@health = health
end

def blam
@health -= 10
puts "#{@name} just got blammed yo."
end

def w00t
@health += 15
puts "#{@name} just got w00ted."
end

def score
@health + @name.length
end

def name=(new_name)
@name = new_name.capitalize
end

def to_s
puts "I'm #{@name} with a health of #{@health} and a score of #{score}"
end
end

这是我的规范文件:

require_relative 'Player'

describe Player do
it "has a capitalized name" do
player = Player.new("larry", 150)

player.name.should == "Larry"
end
end

这看起来对吗?我的问题是关于规范文件的语法。我明白为什么我需要要求 Player 类。但是代码的 describeit 部分在做什么?为什么我需要 it 部分? 似乎只是在定义一个字符串,对吗?

最后,当我从终端运行 rspec player_spec.rb 时,我收到了这个警告:

Deprecation Warnings:

Using `should` from rspec-expectations' old `:should` syntax without explicitly enabling the syntax is deprecated. Use the new `:expect` syntax or explicitly enable `:should` instead. Called from /Users/Jwan/studio_game/player_spec.rb:7:in `block (2 levels) in <top (required)>'.

上面的警告是什么意思?我必须用 enable 语法替换 should 吗?如何启用 :should 语法?为什么 : 应该写成一个符号?

最佳答案

是的,这似乎是正确的。您可能会发现有用的一件事是使用 subject,它可以让您定义一个“主题”以在多个测试中使用:

describe Player do
subject { Player.new("larry", 150) }

it "has a capitalized name" do
expect(subject.name).to eq "Larry"
end
end

这样你就不必在每次测试中一遍又一遍地定义player——subject每次都会自动为你初始化。

describeit 主要用于组织。一个大型项目最终将有数千个测试,一个类的更改可能会导致应用程序完全不同部分的测试失败。保持测试井井有条可以更轻松地发现和修复发生的错误。

至于您的警告,看起来您正在使用告诉您使用“应该”语法的旧指南或教程,但在 RSpec 3 中不推荐使用此语法,而是需要“期望”语法。您可以看到我如何更改上面的代码以使用“expect”语法。这是 a good blog post关于新语法(以及为什么不推荐使用旧语法)。

关于ruby - 第一次在 ruby​​ 中使用 rspec 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26468981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com