简体   繁体   English

Rails模型测试

[英]Rails model testing

Hello I am using rspec to test my user model. 您好,我正在使用rspec来测试我的用户模型。 I just wanted to know if what I am doing is a common practice in testing. 我只是想知道我在做什么是否是测试中的常规做法。 To test for error messages I am doing something like this 为了测试错误消息,我正在做这样的事情

    User.create!(users(:first))
    user.update_attributes  email: 'IDon\'tThinkThisIsAValidEmail' 
    user.should_not be_valid
    assert user.errors.messages.include? :email

Also how would I go about testing for duplicates? 另外,我将如何测试重复项? Calling full_messages and testing for "Email has already been taken" message? 调用full_messages并测试“电子邮件已被占用”消息? Is this a good practice. 这是一个好习惯吗? I am doing tests this way because before my should_not be_valid tests were passing because the username was invalid so that was no good. 我以这种方式进行测试,因为在我的should_not be_valid测试通过之前,因为用户名无效,所以这样做不好。 IS what I am doing a good idea? 我在做一个好主意吗? Any better ways of testing? 有更好的测试方法吗?

You should check out the shoulda gem , which has a suite of useful test assertions, including for uniqueness validations: 您应该检查出Shoulda gem ,它具有一系列有用的测试断言,包括用于唯一性验证的:

describe User do
  should validate_uniqueness_of(:email)
end

Edit: Here's a link to the docs as a great place to start . 编辑: 这是到docs的链接,是开始的好地方

For validating the format of an email you can do something like the following. 要验证电子邮件的格式,您可以执行以下操作。 Note that you don't have to create a user record or use fixtures for writing most validation specs. 请注意,您不必创建用户记录或使用夹具来编写大多数验证规范。

    it "will not allow invalid email addresses" do
      user = User.new(email: 'notAValidEmail')
      user.should have(1).error_on(:email)
    end

    it "will allow valid email addresses" do
      user = User.new(email: 'valid@email.com')
      user.should have(:no).errors_on(:email)
    end

For validating presence you can do this: 要验证状态,您可以执行以下操作:

    it { should validate_presence_of(:email) }

You can see the rspec documentation for more examples: 您可以查看rspec文档以获取更多示例:

https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/model-specs/errors-on https://www.relishapp.com/rspec/rspec-rails/v/2-3/docs/model-specs/errors-on

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM