在 Rails 中,如何测试在控制器中对模型实例进行的修改?

发布于 2024-10-17 00:49:14 字数 810 浏览 7 评论 0原文

我刚刚开始为我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

离笑几人歌 2024-10-24 00:49:14

首先,我会将很多此类功能移至模型中。例如:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文