Rspec-rails: set_fixture_class doesn't work in config.before block

Created on 28 Feb 2012  ·  6Comments  ·  Source: rspec/rspec-rails

This does not work:

RSpec.configure do |config|
  config.before { set_fixture_class :foo => Bar }
end

If I try to run that, it tells me: spec_helper.rb:6:in 'included': undefined method 'set_fixture_class' for FixtureClasses:Module (NoMethodError).

In order to get the equivalent functionality, I need to jump through hoops like:

module FixtureClasses
  extend ActiveSupport::Concern
  included do
    set_fixture_class :foo => Bar
  end
end

RSpec.configure do |config|
  config.include FixtureClasses
end

Most helpful comment

config.before does not quite work when you also have before blocks that reference fixture foo. In those cases the before block closer to the spec gets invoked first, which would again throw FixtureClassNotFound: No class attached to find. Using before(:all) solves it for me.

config.before(:all) do
  self.class.set_fixture_class :foo => Bar
end

All 6 comments

That's because set_fixture_class is a class method, but before hooks run in instance scope. You'll need to do something like:

config.before {
  self.class.class_eval {
    set_fixture_class :foo => Bar
  }
}

Can you just do:

RSpec.configure do |config|
  config.set_fixture_class :foo => Bar
end

@justinko : that gives me undefined method 'set_fixture_class' for #<RSpec::Core::Configuration:0x007fb813d3fe78> (NoMethodError)

@skizzybiz sorry @dchelimsky is right, it is a class method.

Since set_fixture_class is a public method, you can also do this:

config.before do
  self.class.set_fixture_class :foo => Bar
end

config.before does not quite work when you also have before blocks that reference fixture foo. In those cases the before block closer to the spec gets invoked first, which would again throw FixtureClassNotFound: No class attached to find. Using before(:all) solves it for me.

config.before(:all) do
  self.class.set_fixture_class :foo => Bar
end
Was this page helpful?
0 / 5 - 0 ratings