Rails3.2いろいろ奮闘

「テストをしっかりとおこなえば大丈夫」と聞いたけどしっかりとやったことがないのでしっかりとやってみたい。

テーブルを削除する

migrationで作ってみたけどやっぱり使わないとなった古いテーブルを削除したい

kenmituo@HOGE /c/Users/kenmituo/My Documents/Aptana Studio 3 Workspace/support14

$ rails destroy model ArticleRental 
      invoke  active_record
      remove    db/migrate/20121122065546_create_article_rentals.rb
      remove    app/models/article_rental.rb
      invoke    test_unit
      remove      test/unit/article_rental_test.rb
      remove      test/fixtures/article_rentals.yml

kenmituo@HOGE /c/Users/kenmituo/My Documents/Aptana Studio 3 Workspace/support14

$ rails generate migration drop_table_article_rentals
      invoke  active_record
      create    db/migrate/20140501090217_drop_table_article_rentals.rb

編集する

class DropTableArticleRentals < ActiveRecord::Migration
def change
drop_table :article_rentals
end
end

$ bundle exec rake db:migrate
==  DropTableArticleRentals: migrating ========================================
-- drop_table(:article_rentals)
   -> 0.0110s
==  DropTableArticleRentals: migrated (0.0120s) ===============================

articlesテーブルも削除しよっと。

テストに必要なのか?

とりあえず実行した

rake db:test:prepare

ちくしょう、ローカルDBのデータが全て消えた

サーバからバックアップをローカルにコピー、コマンドプロンプトを管理者で実行

mysql -u root -p database_name < "C:\Users\kenmituo\Documents\test\hoge.sql"

不要なテーブルも復活するのでMySQL Workbenchから削除してmigrateしたら怒られた。

テストデータ (fixtures)

サーバのデータのバックアップを使うのでDBの内容を一定に保つ必要がないので使わない。

さていきなり試してみた

rake db:test

developmentのDBが消えたー!!database.ymlで同じDBを指定しているのがダメだめ。

# config/database.yml
development:
  adapter: mysql2
  database: hoge_dev

test:
  adapter: mysql2
  database: hoge_test

あと

create database hoge_test;

ユニットテスト用にファイルを作る

# ./test/unit/hoge_test.rb
# -*- encoding: utf-8 -*-
require "test_helper"

class HogeTest < ActiveSupport::TestCase
  test "Save as hoges objyect" do
    iftb = Hoge.new({
    })
    assert(hoge.save, "no saved hoge")
  end
end

適当なのでメッセージがでるはず

$ rake test:units

    • check_pending!()

c:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.17/lib/active_record/migration.rb:465:in `block in method_missing': undefined method `check_pending!' for # (NoMethodError)
|

こまった、、、コメントアウトしてやる!

#test/test_hepler.rb
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
#  ActiveRecord::Migration.check_pending!
  fixtures :all
end

テストがうごくようになった

$ rake test:units
Run options:
# Running tests:
F
Finished tests in 0.066004s, 15.1506 tests/s, 15.1506 assertions/s.
1) Failure:

失敗したので成功だ。

models/hoge.rb
 validates・・・:presence => true
controllers/hoge_controller.rb
 def new
とか眺めてテストが通るデータを作る。

さて、遅い。テストが遅い。