Rspec 测试验证

Rspec testing validation

我是 rails 的新手,我正在尝试了解使用 Rspec 进行的测试。我创建了一个名为 Contact 的简单模型(仅用于测试目的),其中包含 firstname:string、lastname:string 和 email:string。我只是想为 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

我的理解是此测试不应该 return 任何失败,但确实如此。输出如下:

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 语句从“.to”更改为 "not_to",则测试通过,所以我认为这是倒退的,非常感谢任何帮助或解释。

正如 smathy 在评论中所说,我忘记在我的模型中包含验证。那解决了我的问题。