ruby on rails - Change the order of before hooks in rspec -


i have controller spec :

describe "#create"   before { post 'create', params }   context "when artist valid"     before { allow(artist).to receive(:save).and_return(true) }     { expect(page).to redirect_to(root_path) }     { expect(notifier).to have_received(:notify) }   end end 

this simple spec doesn't work because describe's before block executed before context's before block. so, result of artist.save not stubed when create action called.

it tried :

describe "first describe"   before { puts 2 }   describe "second describe"     before { puts 1 }     "simple spec"       expect(1).to eq 1     end   end end 

i see "2" before "1". i'm not sure think working previous versions.

i know, can :

describe "#create"   context "when artist valid"     before { allow(artist).to receive(:save).and_return(true) }     "redirect root path"       post 'create', params       expect(page).to redirect_to(root_path)     end      "do notifications"       post :create, params       expect(notifier).to have_received(:notify)     end   end end 

but think it's less clean.

i found, on page, http://rubydoc.info/github/rspec/rspec-core/rspec/core/hooks#before-instance_method order should :

before(:suite) # declared in rspec.configure before(:all)   # declared in rspec.configure before(:all)   # declared in parent group before(:all)   # declared in current group before(:each)  # declared in rspec.configure before(:each)  # declared in parent group before(:each)  # declared in current group 

it's not case on example.

i'm not sure think working older versions of rspec.

is there solution?

i recommend against changing order of hooks in rspec. make app non-standard , rails build on standards , having things work expected.

everything you're describing "as designed". outer before blocks called before inner blocks.

your example feel "less clean" standard way controller specs. encourage way more maintainable/readable. not unclean me @ all.

that said, there options:

  1. you can use method. have more once had method do_post or similar
  2. you can use let block initialized lazily. find unlcean if relied on other before blocks running first, it's option.
  3. you can define subject. https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/subject/explicit-subject

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -