在其他测试中重用RSpec测试

时间:2011-11-26 20:20:54

标签: ruby-on-rails testing rspec

对于我的HTML标记,我非常严谨,并遵循严格的表格,列表等编码约定......

我想在我的RSpec测试中包含可重复使用的测试,这将允许我从任何其他测试中调用表单测试并将其直接定位到我正在测试的页面或URL。

这样的事情:

# spec/helpers/form_tester.rb
describe FormTester
  it "should check to see if all the text fields have an ID prefix of 'input-'" do
    ... @form should be valid ...
    should be true
  end
end

# spec/requests/user_form.rb
describe UserForm
  it "should validate the form" do
    @form = find(:tag,'form')
    # call the FormTester method        
  end
end

关于如何做到这一点的任何想法?我正在使用Rails 3.1,RSpec,Capybara和FactoryGirl。

2 个答案:

答案 0 :(得分:9)

使用shared examples。在你的情况下,这样的事情可能有效:

# spec/shared_examples_for_form.rb
shared_examples 'a form' do
  describe 'validation' do
    it 'should be validated' do
      form.should_be valid
    end
  end
end

# spec/requests/user_form.rb
describe UserForm
  it_behaves_like 'a form' do
    let(:form) { find(:tag, 'form') }
  end
end

也可以将参数传递给共享示例,并将共享示例放在spec/support中。请阅读documentation

答案 1 :(得分:1)

共享示例很棒,但您在这里至少遇到两个严重问题。

首先:你为什么要提供表单字段ID?你已经有了非常好的选择器:只需使用input[name='whatever']。即使你 为他们提供ID,也不要在他们身上添加前缀:input#whatever或只是#whatever可能是CSS中比#{1更明智的选择器}}。通过过度选择你的选择器名称,你最有可能使你的CSS和JavaScript比你必须更难写。

第二:不要使用RSpec来测试你的观点。 RSpec在局限于模型时处于最佳状态。对于任何面向用户的人来说,黄瓜更好。

相关问题