简体   繁体   中英

Rspec and Draper : unitialized constant on class name

On Rails 4 when I execute rspec tests for a decorator I got the following error :

/app/spec/decorators/my_decorator_spec.rb:3:in `<top (required)>': uninitialized constant MyDecorator (NameError)

I'm surely missing something but I don't know what.

I generate the decorator

rails g decorator My

A spec/my_decorator_spec.rb file is generated, with the content :

require 'spec_helper'

describe MyDecorator do
end

Then I test

rspec spec/decorators/my_decorator_spec.rb

I didn't add anything in application.rb or spec_helper.rb. The decorator itself works correctly.

EDIT

It's weirder than I expected. When I test all rspec files, tests inside my decorator spec file are correctly executed.

It works :

rspec spec/

It doesn't :

rspec spec/decorators
rspec spec/decorators/my_decorator_spec.rb

This is due to the decorator specs being generated with require 'spec_helper' rather than require 'rails_helper' at the top of the file. When you run other specs before the decorator specs (eg, the controller specs, when running rspec spec/ , since c comes before d), then they end up requiring the right file before your decorator specs get run, so all is well.

The solution is to replace the spec_helper requires with rails_helper in your decorator specs:

perl -pi -e 's/spec_helper/rails_helper/' spec/decorators/*

Once you do that, you should have no problems running rspec spec/decorators .

NB: This change has been made in the draper repo, but it was made after version 2.1.0 of the gem was released, which is the latest non-pre release of the gem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM