[ruby] Merb を使ってみた 2 - fixtures, controller's spec -
前回のつづき、
automigrate によって development 環境の DB はうまく出来てくれるのだけど、テスト環境の DB が反映されない。面倒なのでこうしてしまう。
database.yml
:test: <<: *defaults # :database: db/test.sqlite3 :database: db/development.sqlite3
mkdir db
rake dm:db:automigrate
ここは fixtures が欲しい。
spec/fixtures/articles.yml を作成
birdland: id: 1 title: Lullaby of Birdland body: | Lullaby of birdland, that's what I always hear when you sigh Never in my woodland Could there be words to reveal In a phrase how i feel pathname: lulllaby_of_birdland publish_status: 1 comment_status: 1
fixtures メソッドが存在しない(fixtures を置き換える YamlAdapter なるものが計画されているっぽい)ので
spec_helper.rb に
def fixtures(name) entry = YAML::load_file(File.dirname(__FILE__) + "/fixtures/#{name}.yaml") klass = begin Kernel::const_get(Inflector.classify(Inflector.singularize(name))) rescue nil end unless klass.nil? database.logger.debug { "AUTOMIGRATE: #{klass}" } klass.auto_migrate! (entry.kind_of?(Array) ? entry : [entry]).each do |hash| if hash['type'] Object::const_get(hash['type'])::create(hash) else klass::create(hash) end end else table = database.table(name.to_s) table.create! true table.activate_associations! #pp database.schema (entry.kind_of?(Array) ? entry : [entry]).each do |hash| table.insert(hash) end end end def load_database Dir[File.dirname(__FILE__) + "/fixtures/*.yaml"].each do |path| fixtures(File::basename(path).sub(/\.yaml$/, '')) end end load_database
で、spec/controllers/articles_spec.rb
describe Articles, "index action" do before(:each) do fixtures(:articles) @articles = Article.all end def do_get @controller = dispatch_to(Articles, :index) end it { Article.should_receive(:all).and_return(@articles) do_get @controller.status.should == 200 } end
めでたくレッドからグリーンに変わった。
今日はここまで。