使用 mongoDB 进行 Rspec 测试不起作用

发布于 2024-10-20 19:34:28 字数 1266 浏览 2 评论 0原文

我想使用 Ruby on Rails 和 mongoDB 开发一个小型 Web 应用程序。我使用 Rails 3.0.3 和 mongoid-gem。现在我想用 rspec 做一些测试,但它没有按我的预期工作。测试给出的结果不正确。 这是我想要测试的模型:

class User
  include Mongoid::Document  
  field :nickname, :type => String  
  field :email, :type => String
  field :firstname, :type => String
  field :lastname, :type => String
  field :birthday, :type => Date
  field :picture, :type => String

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :nickname, :presence => true
  validates :email, :presence => true, 
                    :format   => { :with => email_regex }
end

这是不起作用的测试:

require 'spec_helper'

describe User do
  before(:each) do
      @attr = { :nickname => "Example", :email => "[email protected]" }
      @unvalid = {:nickname => "Bla"}
    end

...

it "should reject invalid email addresses" do
      address = "user@foo,com"
      invalid_email_user = User.new(@attr.merge(:email => address))
      invalid_email_user.should_not be_valid
end

当我想要使用 rspec 和 mongoDB/mongoid 进行测试时,是否有一些特别的事情我必须知道?

感谢您的回答

I want to develop a small webapp with Ruby on Rails and mongoDB. I use Rails 3.0.3 and the mongoid-gem. Now I want to do some tests with rspec, but it does not work as I expect. The tests give not the right results.
Here is the model I want to test:

class User
  include Mongoid::Document  
  field :nickname, :type => String  
  field :email, :type => String
  field :firstname, :type => String
  field :lastname, :type => String
  field :birthday, :type => Date
  field :picture, :type => String

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :nickname, :presence => true
  validates :email, :presence => true, 
                    :format   => { :with => email_regex }
end

And here is the test that doesn't work:

require 'spec_helper'

describe User do
  before(:each) do
      @attr = { :nickname => "Example", :email => "[email protected]" }
      @unvalid = {:nickname => "Bla"}
    end

...

it "should reject invalid email addresses" do
      address = "user@foo,com"
      invalid_email_user = User.new(@attr.merge(:email => address))
      invalid_email_user.should_not be_valid
end

Is there something special I must know when I want do to tests with rspec and mongoDB/mongoid?

Thanks for your answers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眉目亦如画i 2024-10-27 19:34:28

试试这个语法。

validates_format_of :email, :with => /[A-Za-z]/

这种格式显然会失败。然后将其替换为您的正则表达式。

Try this syntax.

validates_format_of :email, :with => /[A-Za-z]/

This format will obviously fail. Then replace it with your regex.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文