jpignata/temping

Uninitialized constant when creating more than one model using RSpec

bergera opened this issue · 1 comments

The way the README describes configuring RSpec to use Temping results in a uninitialized constant NameError for every model after the first.

It's not a huge issue as simply changing config.after to config.after(:all) or config.after(:suite) solves the problem, but as I'm just familiarizing myself with Rails/RSpec it took me a while to track this down. Maybe consider updating the README?

Suggested configuration:

Rspec.configure do |config|
  # ...
  config.after do
    Temping.teardown
  end
  # ...
end

Example spec:

require 'rails_helper'

RSpec.describe "something" do
  before(:all) do
    Temping.create :foo
    Temping.create :bar
    Temping.create :baz
  end

  describe "foo" do
    subject { Foo.new }
    it { expect(subject.class).to be Foo }
  end

  describe "bar" do
    subject { Bar.new }
    it { expect(subject.class).to be Bar }
  end

  describe "baz" do
    subject { Baz.new }
    it { expect(subject.class).to be Baz }
  end
end

Results when running example spec with suggested configuration:

$ rspec spec/temping/temping_spec.rb 
.FF

Failures:

  1) something bar 
     Failure/Error: subject { Bar.new }

     NameError:
       uninitialized constant Bar
     # ./spec/temping/temping_spec.rb:16:in `block (3 levels) in <top (required)>'
     # ./spec/temping/temping_spec.rb:17:in `block (3 levels) in <top (required)>'

  2) something baz 
     Failure/Error: subject { Baz.new }

     NameError:
       uninitialized constant Baz
     # ./spec/temping/temping_spec.rb:21:in `block (3 levels) in <top (required)>'
     # ./spec/temping/temping_spec.rb:22:in `block (3 levels) in <top (required)>'

Finished in 0.14291 seconds (files took 2.04 seconds to load)
3 examples, 2 failures

Failed examples:

rspec ./spec/temping/temping_spec.rb:17 # something bar 
rspec ./spec/temping/temping_spec.rb:22 # something baz 
kitop commented

Hi @bergera. What you're mentioning happens because you're creating the temporary tables/models in a before(:all) block, and doing Temping.teardown after each test. As you mentioned, changing the teardown to be after the suite will fix the issue.
Ideally though, temporary tables are created per-test so the environment is clean and independent between specs. So, my suggestion would be to change the before(:all) to just a before which means running that block before each test. You'd notice tests are slightly slower, but it may be worth it as they'd also be more clear.