【问题标题】:How to convert errors_on to RSpec 3 syntax?如何将 errors_on 转换为 RSpec 3 语法?
【发布时间】:2014-06-17 16:10:45
【问题描述】:

我最近从 RSpec 2.99 升级到了 RSpec 3。这将是我的规范之一:

require 'spec_helper'

  describe User, :type => :model do

    it "is invalid without a password" do
      expect(FactoryGirl.build(:user, :password => nil).errors_on(:password).size).to eq(1)      
    end

  end

end

我已经运行了 Transpec gem,它应该将我的大部分规范转换为 RSpec 3 语法。但是,我仍然收到此错误(以及其他一些错误):

 Failure/Error: expect(FactoryGirl.build(:user, :password => nil).errors_on(:password).size).to eq(1)
 NoMethodError:
   undefined method `errors_on' for #<User:0x00000108beaba0>

我尝试以多种不同的方式重新编写测试,但错误不会消失。

有人可以帮忙吗?

【问题讨论】:

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


    【解决方案1】:

    如果您不想捆绑其他 gem,可以在测试对象上调用 valid?,然后访问 errors 数组:

    require 'spec_helper'
    
    describe User, type: :model do
    
      it 'is invalid without a password' do
        user = FactoryGirl.build(:user, password: nil)
        user.valid?
        expect(user.errors[:password].size).to eq(1)
      end
    
    end
    

    【讨论】:

      【解决方案2】:

      看起来它存在于rspec-collection_matchers。你也可以从this issue 修改它。

      【讨论】:

        【解决方案3】:

        一个简单的方法是:

        it "is not valid without a correct email format" do
          user.email = 'user-email.com'
          user.valid?
        
          expect(errors_from session_form, :email).to include('is invalid')
        end
        
        def errors_from(record, attr)
          record.errors[attr].to_sentence
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-09-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多