【问题标题】:RSpec helper specs mock ActiveRecordRSpec 辅助规范模拟 ActiveRecord
【发布时间】:2016-02-26 12:58:46
【问题描述】:

我正在使用 RSpec 进行测试。我经常发现很难编写好的助手规范。这是一个例子:

app/helper/time_helper.rb我有以下代码:

# Returns a text field built with given FormBuilder for given attribute                        |  ~                                                                                                    
# (assumed to be a datetime). The field value is a string representation of                    |  ~                                                                                                    
# the datetime with current TimeZone applied.
def datetime_timezone_field(form_builder, attribute)
  date_format = '%Y-%m-%d %H:%M'
  datetime = form_builder.object.send(attribute)
  form_builder.text_field attribute,
                          value: datetime.in_time_zone.strftime(date_format)
end

测试时,我需要将FormBuilder 传递给该方法。我知道如何创建TestView,但如何创建下面使用的TestModel?在我的规范文件 (spec/helpers/time_helper_spec.rb) 我有类似的东西:

describe '#datetime_timezone_field' do
  class TestView < ActionView::Base; end

  let(:form_builder) do
    ActionView::Helpers::FormBuilder.new(TestModel.model_name.singular,
                                         TestModel.new,
                                         TestView.new,
                                         {})
  end

  it # Some tests here to check the output...
end

我的问题是TestModel。我如何模拟这样的对象?此助手未连接到我的应用程序中的模型。 TestModel 在我的应用程序中应该是“任何模型类”。或者有没有更好的方法编写辅助方法来解决这个问题?

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    无论如何,您实际上并没有测试模型的行为,您只需要一个响应您传入的属性的对象。

    我以为你能做到

    class TestModel
      include ActiveModel::Model
    
      attr_accessor :whatever_attribute
    end
    

    您可能不需要所有ActiveModel,但我不知道表单构建器希望拥有哪些部分。您可以随时查看这些内容。

    所以基本上你会这样做

    let(:form_builder) do
        ActionView::Helpers::FormBuilder.new(TestModel.model_name.singular,
                                             TestModel.new(whatever_attribute: Time.zone.now),
                                             TestView.new,
                                             {})
    end
    

    我没有对此进行测试,但我看不出它不应该工作的任何原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 2015-12-12
      • 1970-01-01
      • 2015-05-13
      • 2014-03-24
      相关资源
      最近更新 更多