Functional Testing

Hey all,

I have a many-to-many relationship (Questions
has_and_belongs_to_many Answers), and when I destroy
the Question (the one) I also destroy all the Answers
(the many).
Since the following doesn’t seem to work for
has_and_belongs_to_many:
class Question < AR::Base…
has_and_belongs_to_many :answers, :dependent =>
:destroy
end

I have this embedded in a transaction block in the
controller action destroy, so that if any of the
destroy actions fail it will roll back.

This all works great, but I’m trying to figure out a
way I can write a functional test that tests one of
the Answer’s failing to destroy and rolling back.
(I’ve tried to lock the database, rename it…but it
doesn’t raise the exception I’m looking for)

Here’s the code I’m working with. Any ideas?

def destroy
begin
Question.transaction() do
Answer.transaction() do
@question = Question.find(params[:id])
for answer in question.answers
if !answer.destroy
#printf (“Answer %s on Question did not
destroy!\n”, answer.id.to_s)
raise ActiveRecord::RecordInvalid.new(answer),
“Error: Answer ID#:”.concat(answer.id.to_s).concat("
on Test ID# “).concat(@exam.id.to_s).concat(” failed
to destory!
Contact Administrator for help! ")
end
end
if !question.destroy
#printf (“Question %s on Section did not
destroy!\n”, question.id.to_s)
raise
ActiveRecord::RecordInvalid.new(question), "Error:
Question ID# “.concat(question.id.to_s).concat(” on
Test ID# “).concat(@exam.id.to_s).concat(” failed to
destory!
Contact Administrator for help! ")
end
flash[:notice] = “Question and all Answers
successfully destroyed!”
redirect_to :action => ‘list’
end
rescue ActiveRecord::RecordInvalid => invalid
redirect_to :action => ‘show’, :id => @exam,
:deleteError => invalid
end
end

Thanks,
Chris Landry

Use a mock object to raise the error you’re looking
for if a flag is set.

test/mocks/test/your_model.rb

require ‘models/your_model’

class YourModel
def destroy
if @raise_error
raise :Exception
else
super
end
end
end


– Tom M.