require 'test/unit' require 'rubygems' require 'active_record' require File.dirname(__FILE__) + '/../init.rb' class ActsAsProxyTest < Test::Unit::TestCase def test_proxy_setup assert Book.ancestors.include?(ActsAsProxy) assert Book.methods.include?('proxies') end def test_singular_proxy assert_nothing_raised do Book.proxies :author, :name end b = Book.new assert b.methods.include?('author_name'), 'book has attribute reader' assert b.methods.include?('author_name='), 'book has attribute writer' assert !b.author, 'book has no author yet' assert_nothing_raised do b.author_name = 'Friedrich Hayek' end assert b.author, 'book has an author now' assert_equal 'Friedrich Hayek', b.author.name, "author's name is set" assert_equal 'Friedrich Hayek', b.author_name, "author's name is availably by proxy" end def test_plural_proxy assert_nothing_raised do Author.proxies :books, :title, :year end a = Author.new assert a.methods.include?('book_title'), 'author has attribute reader' assert a.methods.include?('book_title='), 'author has attribute writer' assert a.methods.include?('book_year'), 'author has book/year proxy as well' assert_equal 0, a.books.size, 'author has no books yet' assert_nothing_raised do a.book_title = 'Road to Serfdom' a.book_year = 1944 end assert_equal 1, a.books.size, 'author has a book now' assert_equal 'Road to Serfdom', a.books.first.title assert_equal 1944, a.books.first.year end end class ActsAsProxyTest class Book < ActiveRecord::Base has_one :author # simulate some attributes attr_accessor :title, :year # overwrite association accessor attr_accessor :author # stub the columns set def self.columns; []; end end class Author < ActiveRecord::Base has_many :books # simulate some attributes attr_accessor :name, :gender # overwrite association accessor attr_writer :books def books @books ||= [] end # stub the columns set def self.columns; []; end end end