簡體   English   中英

在Rails中,如何測試在控制器中對Model實例所做的修改?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM