在单元测试Rails模型中使用shoulda-matcher或Factory Girl是否更好?

时间:2016-02-15 16:29:42

标签: ruby-on-rails unit-testing rspec factory-bot shoulda

我正在练习测试(刚刚进入测试阶段),我想知道在测试模型中使用shoulda-matcher或Factory Girl(或两者兼而有之)是否更好。例如,我目前只使用简单的shoulda-matchers测试,这很好,很直接:

16

但是,根据我的理解,这实际上并没有像Factory Girl那样实例化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 对象。以上“足够”进行测试吗?任何想法都赞赏!

3 个答案:

答案 0 :(得分:2)

factory_girl和shoulda-matchers做了两件不同的事情。大多数Rails应用程序都需要这两种方法。它不是 - 或者。同一个人(Thoughtbot)背后两个宝石的事实是一个很好的线索,它们同时有用。

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

  • shoulda-matchers可以更容易断言您在测试中得到了预期的结果。它提供RSpec匹配器来断言模型和控制器。大多数应用程序都会发现,使用匹配器的ActiveModel匹配器可以确保模型得到很好的验证。 (Personally I get more use out of shoulda-matchers' ActiveModel matchers than the ActiveRecord matchers.

答案 1 :(得分:1)

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

class User
  def fullname
    "#{firstname} #{surname}"
  end
end

工厂/ 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

user_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

答案 2 :(得分:0)

如果您要使用小型模型和测试,您可以使用种子创建示例数据,但如果您要添加功能测试,那么我建议使用FactoryGirl。

我相信所有测试都必须使用.-