Rails代码验证工作但Rspec测试失败

时间:2014-07-02 00:18:07

标签: ruby-on-rails validation ruby-on-rails-4 rspec rspec-rails

任何人都可以看到Rspec的错误吗?我对无效电子邮件的所有测试都失败了(即,它们应该是无效的,但不知何故在Rspec中),但在实际代码中,它工作正常,不允许任何坏的电子邮件。验证甚至可以在我的控制台中使用....

两个注释:

  1. 我意识到格式化并不理想......以后会有效。这只是我单独写的东西而没有通过并干掉它。
  2. 我也意识到存在一种更简单的方法来在模型中单独验证这些内容,但我想要非常自定义的消息而不参考该属性,我不喜欢我读过的需要的迂回方式完成。
  3. 型号代码

    validate :create_validation, on: :create
    
    def create_validation
        errors[:base] << "Please enter a valid email address to continue" if self.email.blank? || (( /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i =~ self.email) == nil) 
    end
    #The RegEx is from Michael Hartl's tutorial
    

    规范代码

    describe Signup do
    
    before do
        @signup = FactoryGirl.create(:signup)
    end
    
        subject { @signup }
    
        describe "email tests" do
          describe "invalid tests" do 
            # blank email
            before { @signup.email = " " }
            it { should_not be_valid }
    
            # invalid format email
            addresses = %w[user@foo..com, user@foo,com user_at_foo.org example.user@foo. foo@bar_baz.com foo@bar+baz.com]
            addresses.each do |invalid_address|
              before { @signup.email = invalid_address }
              it { should_not be_valid }
            end
          end
        end
    end
    

    规范助手中的工厂女孩​​代码

    FactoryGirl.define do
      factory :signup do |f|
        f.email { Faker::Internet.email }
                #... other attributes
      end
    

1 个答案:

答案 0 :(得分:1)

据我所知,您只在创建时验证代码!但是在测试中你在块之前创建了对象并且它在测试中持久存在 - 因此跳过了验证。

尝试此变体

describe Signup do

  before do
    @signup = FactoryGirl.build(:signup)
  end

  subject { @signup }

  describe "email tests" do
    describe "invalid tests" do 
      # blank email
      before { @signup.email = " " }

      it { should_not be_valid }

      # invalid format email
      addresses = %w[user@foo..com, user@foo,com user_at_foo.org example.user@foo. foo@bar_baz.com foo@bar+baz.com]
      addresses.each do |invalid_address|

        before { @signup.email = invalid_address }
        it { should_not be_valid }
      end
    end
  end
end

我希望验证会在已建成但未保存的记录中触发。

PS或者你可以删除选项on: :create