我创建了一个 FormBuilder 扩展:
form.div_field_with_label(:email)
哪个输出:
<div class="field email">
<label for="user_email">Email</label>
<input class="input" id="user_email" name="user[email]" type="email" value="">
</div>
如何在我的 rspec 测试中创建或模拟模板对象?
应用程序/助手/form_helper.rb
module FormHelper
class GroundedFormBuilder < ActionView::Helpers::FormBuilder
def div_field_with_label(key, &block)
if block_given?
content = self.label(key)
content << block.call(key)
end
classes = ['field']
classes << key.to_s
if @object.errors[key].size != 0
classes << 'warning'
msg = @object.errors.full_message(key, @object.errors[key].join(', '))
content << @template.content_tag(:p, msg, :class => "error-message warning alert" )
end
@template.content_tag(:div, content, :class => classes.join(' ').html_safe)
end
end
end
规范/助手/form_helper_spec.rb
require 'spec_helper'
describe FormHelper do
describe FormHelper::GroundedFormBuilder do
describe 'div_field_with_label' do
# how do i create or mock template?
# template = ?
let(:resource) { FactoryGirl.create :user }
let(:helper) { FormHelper::GroundedFormBuilder.new(:user, resource, template, {})}
let(:output) { helper.div_field_with_label :email }
it 'wraps input and label' do
expect(output).to match /<div class="field">/
end
it 'creates a label' do
expect(output).to match /<label for="user[email]">Email/
end
end
end
end