matsko
matsko

Reputation: 22183

Reusing RSpec tests in other tests

I'm very rigorous when it comes to my HTML markup and I follow a strict coding convention for forms, lists, etc...

I would like to include reusable test in my RSpec tests that would allow for me call a form test from any other test and target it directly to the page or URL that I'm testing.

Something like this:

# 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

Any ideas on how todo this? I'm using Rails 3.1, with RSpec, Capybara and FactoryGirl.

Upvotes: 2

Views: 4428

Answers (2)

htanata
htanata

Reputation: 36944

Use shared examples. In you case, something like this may work:

# 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

It's also possible to pass parameters to shared examples and place the shared examples inside spec/support. Just have a read at the documentation.

Upvotes: 12

Marnen Laibow-Koser
Marnen Laibow-Koser

Reputation: 6337

Shared examples are great, but you've got at least two serious problems here.

First: why are you giving your form fields IDs at all? You've already got perfectly good selectors: just use input[name='whatever']. And even if you are giving them IDs, don't put a prefix on them: input#whatever or just #whatever is probably a more sensible selector in your CSS than #input-whatever. By being overspecific on your selector names, you're most likely making your CSS and JavaScript harder to write than they have to be.

Second: don't use RSpec to test your views. RSpec is at its best when confined to models. Cucumber is better for anything user-facing.

Upvotes: 1

Related Questions