【问题标题】:Shoulda testing format应该测试格式
【发布时间】:2010-06-09 16:32:32
【问题描述】:

我正在尝试使用以下格式测试模型的属性:

# myapp/test/unit/comment_test.rb
require 'test_helper'

class CommentTest < ActiveSupport::TestCase
  should_belong_to :article

  should_validate_presence_of :name
  should_validate_presence_of :email
  should_validate_presence_of :content
  should_validate_presence_of :article_id

  should_not_allow_values_for :name, "123", "bob_y", "dave!"
  should_allow_values_for :name, "Bob", "Joe Smith"

  should_not_allow_values_for :email, "abc", "!s@abc.com", "a@!d.com", "a@a.c0m"
  should_allow_values_for :email, "example@example.com", "1a@a.com", "a@2a.net"
end


# myapp/app/models/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :article

  validates_presence_of :name
  validates_presence_of :email
  validates_presence_of :content
  validates_presence_of :article_id

  validates_format_of :name, :with => /\b[\w]+\b/i
end

我在其他模型中进行了类似的验证并且效果很好,但是在这个模型中我遇到了这些错误:

  2) Failure:
test: Comment should not allow email to be set to "!s@abc.com". (CommentTest)
[/Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/assertions.rb:67:in `assert_rejects'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/active_record/macros.rb:139:in `__bind_1276100388_113010'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `call'
 /Library/Ruby/Gems/1.8/gems/thoughtbot-shoulda-2.10.2/lib/shoulda/context.rb:351:in `test: Comment should not allow email to be set to "!s@abc.com". ']:
Expected errors when email is set to "!s@abc.com", got errors: name can't be blank (nil)name is invalid (nil)content can't be blank (nil)article_id can't be blank (nil)

我应该在每次测试中都得到这个,如果重要的话,我也在使用 Factory Girl。

【问题讨论】:

    标签: ruby-on-rails unit-testing validation shoulda factory-bot


    【解决方案1】:

    您的评论模型不验证电子邮件格式。您正在做的事情没有任何问题,您的测试没有通过,因为您的代码不正确,无法通过测试。

    将电子邮件格式的验证添加到您的评论类。

    validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
    

    然后你的测试应该通过了。

    【讨论】:

    • 哇,我不知道为什么我没有看到,一定是工作太晚了。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-04
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多