Hi, I am just starting out writing unit tests, and perhaps someone could
be kind enough to explain why I am seeing this behaviour:
First, my model looks like this:
Author <-HABTM-> Paper
With a model named ‘authors_papers’ which belongs_to :author and :paper.
This is to act as a lookup table which I believed Rails would do
automatically if set up like this.
This is my testing code, testing the Author model:
# Tests the Author<->Paper linkage through the automatic use of
# the author_papers model by Rails.
a = Author.new
p = Paper.new
assert_not_nil a
assert_not_nil p
assert a.save
assert p.save
# 1. Does the linkage work, returning an empty set?
assert_equal a.papers, []
# 2. Can we assign a paper to the author?
assert a.papers << p
assert a.save
assert_not_equal a.papers, []
# 3. Can we pull that paper out (read) again?
assert a.papers.include?(p)
# 4. Can we find the author from the paper?
assert_not_nil p.authors
assert p.authors.include?(a)
# 5. Can we update through the link?
assert p.authors.first.update_attributes(:lastname => "abc") #
Succeeds
assert_equal("abc", p.authors.first.lastname) #
Succeeds
puts "A.Lastname: #{a.lastname}" # =>
<nil>
puts p.authors.first.lastname # =>
abc
assert_equal a, p.authors.first #
Succeeds
assert_equal("abc", a.lastname) #
Fails!
The problem is in the last assertion - surely a.lastname should be set
to ‘abc’ as we did that through the relationship from the Paper? Any
help would be much appreciated, thanks.