LoginSignup
5
4

More than 5 years have passed since last update.

規約に従っていないモデルをグローバルFixtureとして定義する(rspec-rails-1.3.4)

Posted at

どのexampleでもロードさせたいFixtureについては、spec_helperに定義すると便利です。

spec_helper.rb
Spec::Runner.configure do |config|

  config.global_fixtures = :table_name

end

ところが、テーブル名は"table_names"で、モデル名は"ModelName"というように、ActiveRecordの規約に従っていない場合、以下のようなエラーが出てロードできません。

Unable to load table_name, underlying cause no such file to load -- table_name

もちろん、ExampleGroupの中でFixturesを宣言する場合は、以下のようにset_fixture_classを定義すれば、テーブル名とモデル名をマッピングしてロードしてくれます。

hoge_spec.rb
describe 'hoge' do
  set_fixture_class :table_names => ModelName
  fixtures :table_names

end

グローバルなfixturesではどうしたらいいのでしょうか?それらしきメソッドは探してもありませんでした。

そこで、rspec-railsのソースをみてみると、global_fixtures=などのメソッドは、ActiveSupport::TestCaseのクラスメソッドを呼んでいるだけでした。試しに、以下のように書くと、グローバルfixtureもロードされるようになりました。

spec_helper.rb
Spec::Runner.configure do |config|

 ActiveSupport::TestCase.set_fixture_class :table_names => ModelName
  config.global_fixtures = :table_names

end

参考: https://github.com/dchelimsky/rspec-rails/blob/master/lib/spec/rails/extensions/spec/runner/configuration.rb

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4