[英]In Rails how do I test modifications to an instance of a Model that are made in a controller?
我只是为我的Rails应用程序编写测试套件而沾沾自喜。 我在Rails 3应用程序上使用Factory Girl和Shoulda。 在我的控制器中我有:
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
我的问题是如何编写测试验证@ topic.last_post_at获得时间戳并正确保存,我会将此测试写为功能测试还是单元测试?
首先,我会将大量此功能转移到模型中。 例如:
class Topic
after_create :set_defaults
protected
def set_defaults
update_attributes :last_poster => self.user, :last_post_at => Time.now
end
end
然后我会写一个模型测试来确保时间和用户设置并简化我的控制器代码,如下所示:
def create
@topic = @forum.topics.build(params[:topic].merge({:user => current_user}))
respond_to do |format|
...
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.