Rails 3 + mondoDB + HAML + Rspec + Jquery のインストール - 2
前回 の続き。
主に FactoryGirl と MongoMapper の話。基本的に何も考えなくてもそのまま使えるのだけど。
まず、設定。
spec_helper.rb で、
config.use_transactional_fixtures = true
を
config.use_transactional_fixtures = false
にする。そうしないと、ActiveRecord::TestFixtures が呼ばれてしまうのだけど、ActiveRecordを入れてないので落ちる。
そもそもMongoDBにはトランザクションとかないのでfalseでいい。
後は、ActiveRecordで使う場合と同じように、FactoryGirlの定義の読み込みを spec_helper.rb の中で行う。
Factory.find_definitions
mongoDBにはトランザクションがないので、テストの前にデータを自分で消しておいたほうがいいだろう。
config.before(:each) do
MongoMapper.database.collections.each {|collection| collection.remove}
end
全体的にはこんな感じ。generatorが作ったものに、上記変更を入れただけ。
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f}require 'factory_girl' Factory.find_definitionsRSpec.configure do |config| # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr config.mock_with :rspec# config.fixture_path = "#{::Rails.root}/spec/fixtures"# If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, comment the following line or assign false # instead of true. config.use_transactional_fixtures = falseconfig.before(:each) do MongoMapper.database.collections.each {|collection| collection.remove} end end
試しに一個テストを書いてみる。
まず、generatorがEntryクラスのFacotryの雛形も作ってくれているので、それの確認。
File: spec/factories/users.rb
Factory.define :entry do |f|
f.title "MyString"
f.body "MyString"
end
簡単なお試し用のテストを書いてみる。(テスト自体に意味はない)
describe Entry do
it "should create 10 entries" do
10.times { Factory(:entry) }
Entry.count.should == 10
end
end
書いたテストの実行
$ bundle exec rspec spec/models/entry_spec.rb .Finished in 0.03308 seconds 1 example, 0 failures
すばらしい!
FactoryGirlで、MongoMapper::Document同士のassociationも問題なく書ける。(ただし、MongoMapper::EmbeddedDocument から 親Documentへのassociationはうまく作ってくれなかった(正格には作ってくれるんだけど、Saveされない))
こんな感じで、Rails 2 + ActiveRecord時代とほとんど変わらない環境が Rails 3 + MongoMapper で、できたかな。
最近のmongoDB翻訳
しばらくさぼってたんですが、ちょっとずつ再開してます。
ただ、オリジナルのドキュメントの更新頻度がずいぶんと高いので、しばらくは新規のドキュメントはやらずに、既存のドキュメントに追従していくだけにしようと思ってます。とりあえず導入の部分から、ある程度使いこなせるまでの部分だけに集中しようかな、と。
思っていたよりあちこちからリンクされているようで、変に古いドキュメントがあるのは逆にmongoDBにとってマイナスなんで。
とりあえず、以下の超基本ドキュメントを最近更新しました。
Rails 3 + mongoDB + haml + RSpec + jQuery のインストール - 1
会社用の、小物Webアプリを作ろうかと思い、せっかくなのでRuby on Rails 3でmongoDB使ってみようかな、と思い、とりあえず環境を作るところまでのメモ。
Rails 3 のインストール
とりあえず Rails 3 のインストール。現在の最新のbeta4を入れる。Bundlerで。Bundler自体のバージョンが0.9.26以上でないとダメみたいなんで、もしそれ未満しか入っていない場合にはBundlerのインストールからする。
プロジェクトのトップディレクトリとなるところを作成し、そこにGemfileを作る。
$ mkdir ~/workspace/hoge_prj
$ cd ~/workspace/hoge_prj
Gemfile
source 'http://rubygems.org'
gem "rails", "3.0.0.beta4"
rails 3のgemのインストール
$ bundle install
railsコマンドでrailsプロジェクトを作成する。
$ bundle exec rails new . --skip-activerecord --skip-testunit
このコマンド自体がGemfileをもう一度作る。上書きしてしまえばいい。MongoMapperを使う予定なので --skip-activerecord 、rspecを使う予定なので --skip-testunit を指定した。
次に、自分が必要なライブラリをGemfileに追加して、もう一回 bundle install する。
今回は、
gem "mongo_mapper"
gem "bson_ext"
gem "rails3-generators"
gem "haml"
gem "rspec-rails", ">= 2.0.0.beta.13", :require => nil
gem "factory_girl", :require => nil
を追加した。 rspec / haml / factory_girl は普段も使ってるのであまり考えずにそのまま使ってみる。Rails 3では、rspec 2が必要らしい。
$ bundle install
次に、config/application.rb を開いて、
config.generators do |g|
g.orm :mongomapper
g.template_engine :haml
g.test_framework :rspec, :fixture => true
g.fixture_replacement :factory_girl, :dir => "spec/factories"
end
をそれっぽいところに書く。
rspecとhaml、jqueryの関連ファイルを作成する。
$ ./script/rails g rspec:install
$ ./script/rails g haml:install
$ ./script/rails g jquery:install
mongoDBの接続情報が必要なので、それを config/mongodb.yml とかに書き、それを読ませるinitializerも書く。
今回は Mac上にインストールしたmongoDB を使っている。
config/mongodb.yml
base: &base adapter: mongodb host: localhostdevelopment: <<: *base database: hoge-developmenttest: <<: *base database: hoge-testproduction: <<: *base database: hoge-production
config/initializers/mongodb.rb
db_config = YAML::load(File.read(Rails.root.join("config", "mongodb.yml")))if db_config[Rails.env] mongo = db_config[Rails.env] MongoMapper.setup(db_config, Rails.env, :logger => Rails.logger) end
これで、ほぼインストール完了。 rails3-generators のおかげで mongo_mapper を使った scaffold を作ることもできる。
$ ./script/rails g scaffold entry title:string body:string
invoke mongomapper
create app/models/entry.rb
invoke rspec
create spec/models/entry_spec.rb
invoke factory_girl
create spec/factories/entries.rb
route resources :entries
invoke scaffold_controller
create app/controllers/entries_controller.rb
invoke haml
create app/views/entries
create app/views/entries/index.html.haml
create app/views/entries/edit.html.haml
create app/views/entries/show.html.haml
create app/views/entries/new.html.haml
create app/views/entries/_form.html.haml
invoke rspec
create spec/controllers/entries_controller_spec.rb
create spec/views/entries/edit.html.haml_spec.rb
create spec/views/entries/index.html.haml_spec.rb
create spec/views/entries/new.html.haml_spec.rb
create spec/views/entries/show.html.haml_spec.rb
create spec/helpers/entries_helper_spec.rb
create spec/routing/entries_routing_spec.rb
invoke rspec
create spec/requests/entries_spec.rb
invoke helper
create app/helpers/entries_helper.rb
invoke rspec
Plural version of the model detected, using singularized version. Override with --force-plural.
invoke stylesheets
create public/stylesheets/scaffold.css
とりあえず、コンソールからレコード (mongoDB風に言うとドキュメント)が作成できるか確認してみる。
% ./script/rails console
Loading development environment (Rails 3.0.0.beta4)
irb(main):001:0> Entry.create!(:title => "HOGEHOGE", :body => "Hello")
=> #<Entry created_at: Wed, 30 Jun 2010 22:24:06 UTC +00:00, body: "Hello", title: "HOGEHOGE", updated_at: Wed, 30 Jun 2010 22:24:06 UTC +00:00, _id: BSON::ObjectID('4c2bc406a90e08bf25000001')>
irb(main):002:0>
簡単!
本当に保存されたか、mongoシェルで確認してみると、
% ~/somewhere/mongodb-osx-x86_64-1.5.3/bin/mongo
MongoDB shell version: 1.5.3
connecting to: test
type "help" for help
> use hoge-development
switched to db blog-development
> db.entries.find()
{ "_id" : ObjectId("4c2bc406a90e08bf25000001"), "created_at" : "Wed Jun 30 2010 23:24:06 GMT+0100 (BST)", "title" : "HOGEHOGE", "body" : "Hello", "updated_at" : "Wed Jun 30 2010 23:24:06 GMT+0100 (BST)" }
>
入ってる!
サーバを起動して、画面でも見てみる。
config/route.rb に、
resources :entries
と、とりあえず書いて、
$ ./script/rails server
ブラウザで http://localhost:3000/entries/ を開いて確認。



なんとも面白くないいつもの scaffold がちゃんとmongoDBで動いているのが確認できる。
とりあえずここまでで、RSpec / factory_girl あたりを 次回 。
参考:
http://www.mongodb.org/display/DOCS/Rails+3+-+Getting+Started
http://paulbarry.com/articles/2010/01/13/customizing-generators-in-rails-3
http://groups.google.com/group/mongomapper/browse_thread/thread/cd89810b98eb7abf
http://github.com/rspec/rspec-rails
http://stackoverflow.com/questions/3004489/mongodb-initialization-error-in-rails
Mac OS X で mongoDB
出張とか旅行で家を空ける機会が多かったので久しぶりになってしまった。
普段はFreeBSDをサーバ用途で使っているのだけど、Macでも手軽に実行できるので紹介してみる。ダウンロードして展開する以外、特にインストール作業いらない。もろもろなパッケージ管理ツールみたいなものを使ってもいいけど、遊ぶぐらいならこれで十分かな。
とりあえず、 ここ から適当にダウンロード。(OS X 64-bit の 1.5.X とか)
次に、mongoDBのデータを入れるディレクトリを作成。
$ mkdir /somewhere/mongodb_data
後は、ダウンロードして展開したmongodを実行するだけ。
$ /foo/bar/mongodb-osx-x86_64-1.5.3/bin/mongod --dbpath=/somewhere/mongodb_data
オプションを何もつけないとフロントエンドで実行される。バックグランドで実行したい場合には、 --fork --logpath=/somewhere/mongodb.log とか付ける。
接続できるか、mongoコマンドで確認
$ /foo/bar/mongodb-osx-x86_64-1.5.3/bin/mongo
MongoDB shell version: 1.5.3
connecting to: test
type "help" for help
>
エラーが出ないでプロンプトが出たら完了。
後は チュートリアル をやってみるもよし、お好みの言語でいじるもよし、mongoライフを楽しみましょう。
今週のMongoDB翻訳
日本滞在中でいまいち調子が狂う。今週は更新のみ。
- チュートリアル - 内容的に大きな変更なし。ObjectIDの作成に、ObjectID() を使うようになった。
- コネクション - 内容的に大きな変更なし。
- アップデート - $ ポジションオペレータ が追加
- インデックス - ドキュメント自体をインデックスとして使うところの更新