在 Rails 中,如何测试在控制器中对模型实例进行的修改?
我刚刚开始为我的 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 是否带有时间戳并正确保存,以及我是否会将此测试编写为功能测试或单元测试?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我会将很多此类功能移至模型中。例如:
然后我会编写一个模型测试以确保设置时间和用户并简化我的控制器代码,如下所示:
Firstly, I would move a lot of this functionality into the model. For example:
I would then write a model test to make sure that the Time and user get set and simplify my controller code like this: