I'm just getting my feet wet in writing a testing suite for my Rails application. I'm using Factory Girl and Shoulda on a Rails 3 app. In my controller I have:
def create
@topic = @forum.topics.build(params[:topic])
@topic.user = current_user
#So the topic gets pushed to the top without any replies
@topic.last_poster = current_user
@topic.last_post_at = Time.now
respond_to do |format|
if @topic.save
format.html { redirect_to(forum_topic_path(@topic.forum, @topic), :notice => 'Topic was successfully created.') }
format.xml { render :xml => @topic, :status => :created, :location => @topic }
else
format.html { render :action => "new" }
format.xml { render :xml => @topic.errors, :status => :unprocessable_entity }
end
end
end
My question is how would I write test verifying that @topic.last_post_at gets timestamped and saved correctly and would I write this test as a functional test or a unit test?
Firstly, I would move a lot of this functionality into the model. For example:
class Topic
after_create :set_defaults
protected
def set_defaults
update_attributes :last_poster => self.user, :last_post_at => Time.now
end
end
I would then write a model test to make sure that the Time and user get set and simplify my controller code like this:
def create
@topic = @forum.topics.build(params[:topic].merge({:user => current_user}))
respond_to do |format|
...
end
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.