2011-03-09 90 views
0

我想用Ruby on Rails和mongoDB开发一个小型web应用程序。我使用Rails 3.0.3和mongoid-gem。现在我想用rspec做一些测试,但它不像我预期的那样工作。测试没有给出正确的结果。 这里是我想测试模型:使用mongoDB进行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+\-.][email protected][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 = "[email protected],com" 
     invalid_email_user = User.new(@attr.merge(:email => address)) 
     invalid_email_user.should_not be_valid 
end 

是不是有什么特别的,我必须知道,当我想要做的使用RSpec测试和mongoDB/mongoid?

感谢您的回答

+0

您可以添加spec_helper的源代码吗? – 2011-03-09 16:16:38

回答

0

试试这个语法。

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

这种格式将明显失败。然后用你的正则表达式替换它。

+0

嘿很酷,这个工程。非常感谢。 因此,我可以像使用rspec和SQL一样使用rspec和mongoDB? – rotespferd 2011-03-09 17:31:53

+0

@rotespferd是的,你确定可以。只有要注意的是假设你从active_record继承的插件。但是像factory_girl之类的东西通常有一个mongoid适配器。 – 2011-03-09 18:09:51