2016-02-26 65 views
2

我正在使用RSpec进行测试。我经常发现很难写出好的帮手规格。这里有一个例子:RSpec helper specs mock ActiveRecord

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?在我的规格文件(规格/助理/ 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应该是我的应用程序中的“任何模型类”。还是有更好的方法来编写帮助者方法来摆脱这个问题?

回答

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 

我没有测试这一点,但我看不出有任何理由不应该工作。