【问题标题】:Rspec Factory Girl testing class methods?Rspec Factory Girl 测试类方法?
【发布时间】:2015-06-16 18:02:28
【问题描述】:

我是 Rspec 和 Factory Girl 的新手。我用它来测试已经存在的模型。有没有办法使用 Factory Girl 生成的副本从 apps/model 目录中的原始模型测试现有的类方法?

【问题讨论】:

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


    【解决方案1】:

    当然。只需在 spec/models 目录中创建您的规范文件。

    下面是 Certificate 模型的示例 certificate_spec.rb 文件,它应该验证证书是否具有 first_name

    require 'spec_helper'
    
    describe "Certificate" do
      let(:certificate) { FactoryGirl.build(:certificate) }
    
      it "is valid with valid attributes" do
        expect(certificate).to be_valid
      end
    
      it "is not valid without a first name" do
        certificate.firstname_a = nil
        expect(certificate).not_to be_valid
      end
    end
    

    要测试特定的类方法,请根据需要设置模型,使用工厂或通过从工厂创建实例并对其进行修改。

    然后在实例上调用你需要的方法:

    it "should respond to #doSomething with true" do
      expect(certificate.doSomething).to be_true
    end
    

    更新

    正如顾俊超所指出的,我没有提供上面测试类方法的例子。

    根据定义,类方法是在类而不是它的任何实例上定义的。因此,您不需要 FactoryGirl 创建的任何实例即可测试类方法。只需根据班级设定您的期望即可。

    例如,假设User 类提供了用户可以成为成员的角色列表。您可能希望确保以某种方式定义这些角色:

    require 'spec_helper'
    
    describe "User" do
      describe ".available_roles" do
        it "should return anonymous, member, moderator, admin in that order" do
          expect(User.available_roles).to_equal %w{anonymous member moderator admin}
        end
      end
    end
    

    请注意,预期是针对 User 类,而不是针对它的实例。

    【讨论】:

    • 我也是 rspec + factorygirl 的新手。但我很确定你的例子都不是“类方法”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多