【发布时间】: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