我无法理解为什么以下Rspec测试没有通过 -
require "rspec"
require_relative "file-to-be-tested"
describe Customer do
it "is valid with firstname" do
customer = Customer.new("handy")
expect(customer).to be_valid
end
end
用于相应的类定义 -
class Customer
attr_reader :firstname
def initialize(firstname)
@firstname = firstname
end
end
这两个代码段位于同一文件夹中的单独文件中,因此当我在终端中运行~rspec <first-filename>
时,出现以下错误 -
F
Failures:
1) Customer is valid with firstname
Failure/Error: expect(customer).to be_valid
expected #<Customer:0x007f90e50f3110> to respond to `valid?`
# ./poodr/poodr_rspec.rb:8:in `block (2 levels) in <top (required)>'
Finished in 0.00551 seconds (files took 0.52876 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./poodr/poodr_rspec.rb:6 # Customer is valid with firstname
答案 0 :(得分:1)
be_valid
是一个rspec-rails方法,但看起来你只使用直接的rspec。你可以这样做:
require "rspec"
require_relative "file-to-be-tested"
describe Customer do
it "is valid with firstname" do
expect { Customer.new('handy') }.to_not raise_error
end
end
答案 1 :(得分:0)
你期望be_valid测试做什么?问题是Customer类没有名为valid的方法?你的测试试图测试。
如果您正在进行测试驱动的开发,那么就可以进行测试:
class Customer
def valid?
true
end
end
您现在有一个名为valid的方法,您的测试将通过。显然它不应该永远是真的,所以你的下一步将是扩展有效的定义?要知道客户是否有效,需要做哪些检查?