Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share code between view specs

I have several view specs: edit, index, new, show, for a given Rails (3) controller and I'd like to have some of the boilerplate setup code shared between them. I'd like to avoid placing it in the spec_helper.rb file. Any ideas?

To be more specific, in spec/views/steps, I have four files: {edit,new,show,index}.html.erb_spec.rb. I would like for them to share some code, such as

  let(:workflow) do
    document = Factory.create(:document)
    document.user = user
    document.save!
    document.workflow
  end

For example - the exact code does not matter. I would like to do this without putting it in spec_helper.rb.

like image 925
David N. Welton Avatar asked Nov 13 '11 12:11

David N. Welton


2 Answers

You will find that rspec has exactly the thing for this: shared context.

It will allow you to do something like this

shared_context 'workflow' do
  let(:workflow) do
    document = Factory.create(:document)
    document.user = user
    document.save!
    document.workflow
  end
end

If you need to share this between different spec-files, write this in a file that you store inside spec/support. In your test you can then write:

describe 'Something' do
  include_context 'workflow'

  it 'behaves correctly' do
    ...
  end
end

Hope this helps.

like image 179
nathanvda Avatar answered Dec 26 '22 13:12

nathanvda


Maybe you can use a shared context: https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-context

like image 44
fuzzyalej Avatar answered Dec 26 '22 13:12

fuzzyalej