Reorder to hooks in rspec

I have a controller specification like this:

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

This is a simple specification, but it does not work because the description before the block is executed before the context before the block. Thus, the result of artist.save does not fade when the create action is called.

He tried to do this:

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

I see "2" before "1". I'm not sure, but I think it worked with previous versions.

I know I can do this:

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

But I think it is less clean.

I found on this page http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/Hooks#before-instance_method , what should be the order:

 before(:suite) # declared in RSpec.configure before(:all) # declared in RSpec.configure before(:all) # declared in a parent group before(:all) # declared in the current group before(:each) # declared in RSpec.configure before(:each) # declared in a parent group before(:each) # declared in the current group 

This is not the case in this example.

I'm not sure, but I think it worked with older versions of rspec.

Is there a solution?

+4
source share
1 answer

I would strongly recommend that you change the order of the hooks in rspec. This will make your application non-standard and Rails standards, and everything will work as expected.

Everything that you describe is "as intended." External before blocks is always called before internal blocks.

Your example, which you consider β€œless clean,” is the standard way to fulfill controller specifications. I really urge you to do this in a way that makes it more convenient and readable. For me it doesn't look unclean at all.

However, there are several options:

+5
source

Source: https://habr.com/ru/post/1492621/


All Articles