【发布时间】:2013-12-06 03:08:41
【问题描述】:
我在下面有一段代码作为参数,它从 CSV 文件中的一行中获取信息并创建一个 Employee 对象。我是 Rspec 的新手,即使我知道我的解决方案按我想要的方式运行,我似乎也无法通过测试。在我努力学习测试驱动开发的过程中,我想更好地了解 Rspec。我怎样才能编写一个测试来证明这段代码有效?我意识到这个过程应该反过来(在创建最终产品之前先测试),但我这样做是为了尝试了解规范如何更好地工作。如果您需要更多我的代码,请告诉我:
CSV 文件:
first_name,last_name,annual_income,tax_paid,tax_rate
Johnny,Smith,120000,28000,38
Jane,Doe,140000,30000,40
Liz,Lemon,,21000,30
,Orsillio,40000,8800,18
Eric,Schmidt,54000,,28
员工类:
class Employee
attr_reader :last_name, :first_name, :annual_income, :tax_paid, :tax_rate
def initialize(attributes) **#<-where the csv row is being passed in but in another main file used to run the code**
@last_name = attributes['last_name'] ||="[Last Name]"
@first_name = attributes['first_name'] ||="[First Name]"
@annual_income = attributes['annual_income'].to_f ||= 0
@tax_paid = attributes['tax_paid'].to_f ||= 0
@tax_rate = attributes['tax_rate'].to_f ||= 0
end
end
几个 Rspec 测试尝试之一:
require 'rspec'
require_relative 'employee'
describe Employee do
it 'instantiated Employee class object should instantiate when missing arguments are passed in' do
expect(Employee.new("").first_name).to eql("[First Name]")
end
end
这是测试的结果:
F
Failures:
1) Employee instantiated Employee class object should instantiate when missing arguments are passed in
Failure/Error: expect(Employee.new("").first_name).to eql("[First Name]")
IndexError:
string not matched
# ./employee.rb:9:in `[]='
# ./employee.rb:9:in `initialize'
# ./employee_spec.rb:6:in `new'
# ./employee_spec.rb:6:in `block (2 levels) in <top (required)>'
Finished in 0.00029 seconds
1 example, 1 failure
Failed examples:
rspec ./employee_spec.rb:5 # Employee instantiated Em
【问题讨论】:
-
你能显示测试的结果吗?
-
@jamesw 我刚刚添加了测试的结果输出
-
看起来您的测试运行良好!我刚刚复制了您的课程代码并尝试从 rails 控制台运行它,并且您的课程中确实存在相同的错误。所以你的问题应该是,“我怎样才能修好我的课?”虽然没有任何线索
-
好的,找出您的问题并添加了答案。如果有帮助请采纳
标签: ruby csv rspec tdd automated-tests