问题
When running my tests I get this error:
FixtureClassNotFound: No class attached to find
What causes this error and how to fix it?
回答1:
Most likely this happens because a custom table name is used for a Model (using the set_table_name) or the model is in a module.
To solve, you need to add a set_fixture_class
line in the test_helper.rb
before the fixtures :all
line:
class ActiveSupport::TestCase
self.use_transactional_fixtures = true
.
.
.
set_fixture_class my_table_name: MyModule::MyClass
fixtures :all
end
In this case the fixtures file should be called my_table_name.yml
回答2:
NOTE: It would be helpful if you included the stack trace and the full error message.
In your test/test_helper.rb class, there is a line like
fixtures :all
This tells the framework to look in the directory test/fixtures and try to load each of the YAML files that it sees there and then save them to the DB. So my hunch is that you have a file in there that does not have class in app/models with the singularized name. In other words, if there is a file test/fixtures/posts.yml, then when you run your tests, the framework will look for a class named Post to load your data in.
So the first thing I would do is check to see if you have a fixture file that is not associated with one of your model classes (maybe you deleted a model but forgot to delete the fixture?)
If that doesn't work, try changing the line in your test helper to explicitly load the fixtures you need. So if you only want to load fixtures for an object named Post and an object named User, you will change:
fixtures :all
to
fixtures :posts, :users
in test_helper.rb and you should see the error go away (although other errors may now appear because your fixtures are not loaded.0
回答3:
I got this error when I made a mistake generating some scaffold code. I used a plural model name, and that just confused the fixture loading, I guess. Regenerating the scaffold with a singular model name fixed the problem.
回答4:
In the Event that the Class is an irregular class in terms of naming such as fish
, sms
it could have been created by using the --force-plural
flag
i.e
rails g model sms --force-plural
in that case you would set up an inflection which is set up under
config/initializers/inflections.rb
an example of such is this
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.plural /^(ox)$/i, '\1en'
inflect.singular /^(ox)en/i, '\1'
inflect.irregular 'person', 'people'
inflect.uncountable %w( fish sheep )
end
In this way the class can be recognized as you declared it
来源:https://stackoverflow.com/questions/7020494/how-do-you-solve-fixtureclassnotfound-no-class-attached-to-find