Ruby on rails 在单元测试Rails模型中使用shoulda matchers或Factory Girl更好吗?

Ruby on rails 在单元测试Rails模型中使用shoulda matchers或Factory Girl更好吗?,ruby-on-rails,unit-testing,rspec,factory-bot,shoulda,Ruby On Rails,Unit Testing,Rspec,Factory Bot,Shoulda,我正在练习测试(刚刚开始),我想知道在测试模型中使用shoulda matchers或Factory Girl,或者两者的组合是否更好。例如,我目前只使用简单的shoulda matchers测试,这是一个简单明了的测试: RSpec.describe User, :type => :model do describe User do it { should validate_presence_of(:username) } it { should

我正在练习测试(刚刚开始),我想知道在测试模型中使用shoulda matchers或Factory Girl,或者两者的组合是否更好。例如,我目前只使用简单的shoulda matchers测试,这是一个简单明了的测试:

RSpec.describe User, :type => :model do
    describe User do
        it { should validate_presence_of(:username) }
        it { should validate_presence_of(:password_decoded) }
        it { should validate_length_of(:password).is_at_least(3) }
        it { should validate_presence_of(:session_token) }
        it { should have_one(:shopping_cart)}
    end
end

但是,根据我的理解,这实际上并不像Factory Girl那样实例化
用户
对象。上述内容是否足以进行测试?任何想法都很感激

对于基本的关联和验证,我认为shoulda matchers很好。我使用工厂来测试其他方法和更复杂的验证。下面是一个基于实例属性返回值的方法的简单示例。我还展示了如何使用sequence始终生成一个唯一的电子邮件地址,这在测试中经常会让您绊倒

class User
  def fullname
    "#{firstname} #{surname}"
  end
end
factories/users.rb

FactoryGirl.define do
  sequence(:username) { |n| "user-#{n}" }

  factory :user do
    email { |_u| "#{FactoryGirl.generate(:username)}@example.com" }
    password              'password'
    password_confirmation 'password'
    firstname             'John'
    surname               'Smith'
  end
end
用户_spec.rb

RSpec.describe User do

  describe "#fullname" do
    it "returns the first and surnames separated by a space" do
      user = FactoryGirl.create(:user)
      expect(user.fullname).to eq "John Smith"
    end
  end
end

如果您打算使用小型模型和测试,您可以使用seed创建示例数据,但是如果您也打算添加功能测试,那么我建议使用FactoryGirl


我相信所有的测试都必须有一个匹配者。

工厂女孩和匹配者做两件不同的事情。大多数Rails应用程序都需要这两种功能。不是非此即彼。两个宝石背后都是同一个人(Thoughtbot),这一事实是一个很好的线索,表明它们在同一时间都很有用

  • factory_girl允许您创建(仅在内存或数据库中)用于测试的对象。大多数应用程序需要在测试中反复创建类似的对象;factory_girl在这样做时消除了重复。它还允许您轻松自定义预定义对象(例如,比Rails夹具更容易)。您展示的模型规范不需要factory_girl,但是如果您的模型中有任何代码比基本配置更复杂,那么使用factory_girl创建要测试的模型可能会有所帮助

  • shoulda matchers可以更容易地断言您在测试中得到了预期的结果。它提供了RSpec匹配器,用于断言有关模型和控制器的内容。大多数应用程序会发现shoulda matchers的ActiveModel matchers在确保其模型得到良好验证方面非常有用。()


如果你有一个
用户说
有很多:posts
,你会说使用FactoryGirl创建对象(在测试数据库中)和验证关联是多余的(可能希望不是零)-当你可以只使用shoulda匹配器时?我可能根本不会测试
有很多
。我无法想象一个
有多少个
还没有被某个验收规范(RSpec特性规范或Cucumber规范)彻底测试过。正如我链接到的答案所说,这就是我对ActiveRecord matchers的总体看法。我应该补充一个例外:有时候,匹配器应该是测试
所属
依赖
选项的正确方法。