なんか、テスト書くのに飽きてきたwww
つうか、ね?
functionalテストって、やることって、アクセスできるかとか、リダイレクトしてるかとか、そんなのばっかりじゃん?
で、unitテストって、やることって、まず、なんかのメソッドなりロジックなりを作らないと、やることない訳じゃん?
つまんねぇwww
なんで、ちょっと、別のことやる。
SNSなんだから(hogehogeって、SNSだったんだw)、やっぱり、お友達機能、技術的な方面のアプローチで云えば、ユーザ同士の連携、が、不可欠な訳でして。
つう訳で、自己参照型の多対多の関連付けが必要な訳ですな。
で、前にもUserとRoleで多対多の関連付けをhabtmでやってるけど、今回は、has_many :throughでやろうかな、と。
なんで? って、やっぱり、それは、こう...あれですよ。こっちが友達だと思っていても、向こうが友達だと思っているとは限らないからwww
あるよね? よくあるよね?www
いやいや、そうじゃあ、なくってwww
友達にクラスを付けられるようにしたかったから。
顔見知りと、遊び友達と、親友とじゃあ、やっぱり違うじゃん?
まあ、そんなことを考えて。
んで、参考は、この辺。
で、とりあえず、モデル作る。
$ script/generate model Friend
んで、マイグレーション・ファイルの編集
db/migrate/*数字*_create_friends.rb
class CreateFriends < ActiveRecord::Migration def self.up create_table :friends do |t| t.column "my_id", :integer, :null => "false" t.column "friend_id", :integer, :null => "false" t.timestamps end end def self.down drop_table :friends end end
friendモデルの編集。
app/models/friend
class Friend < ActiveRecord::Base belongs_to :friend_shipped, :foreign_key => :friend_id, :class_name => "User" belongs_to :befriend_shipped, :foreign_key => :my_id, :class_name => "User" end
userモデルの編集
app/models/user
+ has_many :friend_ships, :foreign_key => 'my_id', + :class_name => 'Friend', + :dependent => :destroy + has_many :befriend_ships, :foreign_key => 'friend_id', + :class_name =>'Friend', + :dependent => :destroy + has_many :friends, :through => :friend_ships, + :source => :friend_shipped + has_many :be_friends, :through => :befriend_ships, + :source => :befriend_shipped
はい。やること終わりwww
んじゃあ、テスト。
まず、フィクスチャ。
test/fixtures/friernds.yml
# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html quentin_has_friend_ship_to_aaron: my_id: 1 friend_id: 2
いや、いいのよw
quentinが、勝手にaaronを「友達」だと思っているだけで、aaronはquentinを友達だとは思っていないからwww
んで、unitテスト。
require File.dirname(__FILE__) + '/../test_helper' class FriendTest < ActiveSupport::TestCase test "should user has friend shipped" do user = users(:quentin) assert_equal(user.friends.count, 1) end test "should user has befriend shipped" do user = users(:aaron) assert_not_equal(user.friends.count, 1) assert_equal(user.be_friends.count, 1) end end
なんか、rails 2.0からは、必要なフィクスチャは、勝手に読み込まれるようになったらしいんで、あえてfixtures宣言は書いていない。
んで、テスト。
$ ruby test/unit/friend_test.rb => Loaded suite test/unit/friend_test => Started => .. => Finished in 0.046649 seconds. => => 2 tests, 3 assertions, 0 failures, 0 errors
おk。
つうか、ね?
こんなに簡単に、事は済んでないのよwww
TextMateで書いていると、「ファイルを保存する」と云う行為を忘れがちで(Save Automatically when Focus Is Lostをactiveにしている)www
んで、フィクスチャ書き換えながらやってたら、はまるはまるwwwwww
まあ、これでユーザ間の連携がとれるようになったよね。
じゃあ、またペルシャの王子になりますかwww <= コード書けよ、俺...