rails rspec controller action对象方法stub

时间:2013-11-22 21:29:03

标签: ruby-on-rails rspec

我正在尝试测试我的控制器#merge_with动作。我想测试@article不是nil,并获得分配在数据库中找到的文章。不确定为什么测试失败,因为该操作似乎在浏览器中工作正常。

控制器#merge_with action。

def merge_with 
  unless current_user.admin?
    flash[:error] = _("You are not allowed to perform a merge action")
    redirect_to :action => :index
    return
  end
  @article = Article.find_by_id(params[:id])
  if @article.merge_with(params[:merge_with])
    flash[:notice] = _("Articles successfully merged!")
    redirect_to :action => :index
  else
    flash[:notice] = _("Articles couldn't be merged")
    redirect_to :action => :edit, :id => params[:id]
  end
end

由于在@article对象上调用了merge_with,我对重定向的RSpec测试失败了。

context "when user is admin" do
  before :each do
    @admin_user = Factory(:user, :profile => Factory(:profile_admin))
    @article = Factory(:article, :user => @user)
    request.session = {:user => @admin_user.id}
  end

  it "should merge articles" do
    Article.should_receive(:find_by_id).with(@article.id).and_return(@article)
    post :merge_with, id: @article.id
    assigns(:article).should == @article
  end
end

错误讯息

expected: #<Article id: 1, type: "Article", title: "A big article", author: nil, body: "A content with several data", extended: "extended content for fun", excerpt: nil, created_at: "2013-11-22 21:19:38", updated_at: "2013-11-22 21:19:36", user_id: nil, permalink: "a-big-article", guid: "deadbeef2", text_filter_id: nil, whiteboard: nil, name: nil, published: true, allow_pings: true, allow_comments: true, published_at: "2005-01-01 02:00:00", state: "published", parent_id: nil, settings: {}, post_type: "read">
        got: nil (using ==)

1 个答案:

答案 0 :(得分:1)

我会检查一些事情:

  • 您之前有可能干扰的过滤器吗?请执行“放置response.body.inspect”并检查方法的输出是否不是某些重定向(实际上,您的“除非current_user.admin?”重定向应该是一个过滤器,因此您可以将其重用于其他操作需要管理员)

  • 您还可以通过一些调试来检查方法内部发生了什么,我的意思是,current_user是一个有效的管理员吗?请将“put current_user.inspect”置于除非之前,如果它有效,则在find_by_id之前执行“puts @ article.inspect”,如果找不到@article = Article.find_by_id(params [:id])会发生什么?如果id无效,你有一些错误因为你在nil上调用merge_with。

调试那个,你最终得到你的错误的答案,我猜它只是“除非current_user.admin?”重定向你,所以永远不会分配@article。