我是rails的新手,我正试图理解使用Rspec的测试。我创建了一个名为Contact的简单模型(仅用于测试目的),其中包含名:字符串、姓:字符串和电子邮件:字符串。我只是想设置一个测试firstname失败,如果是空的。
我的Rspec测试如下:
describe Contact do
it "creates a valid model" do
contact = Contact.new(
firstname: 'firstname',
lastname: 'lastname',
email: 'email'
)
expect(contact).to be_valid
end
it "is invalid without a firstname" do
contact = Contact.new(firstname: nil)
contact.valid?
expect(contact.errors[:firstname]).to include("can't be blank")
end
我的理解是这个测试不应该返回任何失败,但它确实返回了。以下输出:
Failures:
1) Contact is invalid without a firstname
Failure/Error: expect(contact.errors[:firstname]).to include("can't be blank")
expected [] to include "can't be blank"
# ./spec/models/contact_spec.rb:16:in `block (2 levels) in <top (required)>'
Finished in 0.11659 seconds (files took 2.39 seconds to load)
18 examples, 1 failure, 15 pending
Failed examples:
rspec ./spec/models/contact_spec.rb:13 # Contact is invalid without a firstname
如果我将expect语句从"。到"not_to"的测试通过了,所以我认为我把这个搞反了,任何帮助或解释都是非常感谢的。
正如smarthy在评论中所说,我忘记在模型中包含验证。