新手问题 RSpec 的一些问题

Catherine · May 24, 2016 · Last by catherine replied at May 25, 2016 · 2049 hits
it "is invalid with a duplicate email address" do
  Contact.create(
    firstname: 'Joe', lastname: 'Tester',
    email: '[email protected]')
  contact = Contact.create(
    firstname: 'Jane', lastname: 'Tester',
    email: '[email protected]')
  expect(contact).to have(1).errors_on(:email)
end

expect(contact) 的类型是 RSpec::Expectations::ExpectationTarget

model 有 email 的唯一性验证,但跑测试说没有 have 这个方法,搞不明白为啥?

这是《Everyday Rails Testing With Rspec》上的例子吧,可能你看的版本比较旧了,新版给你参考下:

it "is invalid with a duplicate email address" do
  Contact.create(firstname: 'Joe', lastname: 'Tester', email: '[email protected]' )
  contact = Contact.new(firstname: 'Joe', lastname: 'Tester', email: '[email protected]' )
  contact.valid?
  expect(contact.errors[:email]).to include("has already been taken")
end

#1 楼 @night_7th 是的,但我是才买几周的,整个项目都是参考的案例,ruby、rails 版本也是一致的。怎么没法用 have 方法....不明白

记得以前有类似这样的弄法:

it { expect(subject).to validate_presence_of :email }
it { is_expected.to validate_presence_of :email }
it { should validate_presence_of :email }

#5 楼 @qinfanpeng 谢谢!之前安道的书籍 5 折优惠,果断买了,以为是一直同步更新的... 1 楼的回答的时候我还纳闷:我才买的,怎么不是‘最新的’?囧。。只能一边当作参考了

You need to Sign in before reply, if you don't have an account, please Sign up first.