简体   繁体   English

Rails Minitest model 方法测试

[英]Rails Minitest model method test

I've got User model method which calculate a number of user membership.我有 User model 方法,它计算用户成员的数量。 I want to it test by MiniTest.我想通过 MiniTest 对其进行测试。 Here is what I have:这是我所拥有的:

  def member_for
    time_diff = Time.current - created_at
    result = ActiveSupport::Duration.build(time_diff.to_i).parts
    return "Member for #{result[:years]}y, #{result[:months]}m" if result.key?(:years) && result.key?(:months)

    if result.key?(:years) && result.key?(:days)
      "Member for #{result[:years]}y, #{result[:days]}d"
    elsif result.key?(:months)
      "Member for #{result[:months]}m"
    elsif result.key?(:days)
      "Member for #{result[:days]}d"
    end
  end

I was trying to write some MiniTest:我正在尝试编写一些 MiniTest:

  test 'member for' do
    user.created_at = 2.years.ago + 3.months + 2.days
    user.member_for
  end

  private

  def user
    @user ||= users(:one)
  end

But to be honest, I don't know how to compare if it returns the correct string.但老实说,我不知道如何比较它是否返回正确的字符串。

You can decrease the cyclic complexity as well as removing several bugs which give the wrong duration (by omitting weeks and months) by simply iterating across the parts:您可以通过简单地遍历各个部分来降低循环复杂性并删除几个给出错误持续时间的错误(通过省略几周和几个月):

  def member_for
    time_diff = Time.current - created_at
    parts = ActiveSupport::Duration.build(time_diff.to_i).parts
    formatted = parts.except(:seconds).map do |unit, value|
      "#{value} #{unit}"
    end
    "Member for #{formatted.to_sentance}"     
  end

You can use a simple lookup table or the I18n API if you want to have abbreviations instead of the full unit names.如果您想使用缩写而不是完整的单位名称,可以使用简单的查找表或I18n API。 Array#to_sentance is from ActiveSupport. Array#to_sentance来自 ActiveSupport。

You would then test this by:然后,您将通过以下方式进行测试:

class MemberTest < ActiveSupport::TestCase
  test 'member_for without weeks' do
    user.created_at = 2.years.ago + 3.months + 2.days
    assert_equal(user.member_for, 'Member for 1 year, 3 months and 2 days')
  end

  test 'member_for with weeks' do
    user.created_at = 2.years.ago + 2.weeks
    assert_equal(user.member_for, 'Member for 1 year and 2 weeks')
  end

  private

  def user
    @user ||= users(:one)
  end
end

However its questionable if this code really belongs in a model in the first place since its presentation and not buisness logic.然而,如果这个代码真的属于 model,那么它是否真的属于自它的呈现而不是商业逻辑以来的首位。 I would say a helper or decorator/presenter is more suitible then cramming more logic into your models.我会说帮助者或装饰者/演示者更合适,然后将更多逻辑塞入您的模型中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM