测试 [提问] 功能测试中的一个迷惑

woaigithub · 2012年12月04日 · 最后由 woaigithub 回复于 2012年12月04日 · 3003 次阅读
def test_should_create_post_successfully
    user = FactoryGirl.create(:user_valid)
    category = FactoryGirl.create(:category_valid)
    #@request.session[:user_id] = user.id
    assert_difference('Post.count') do

      article = FactoryGirl.create(:post_valid)

      post :create, {:post=>{:category_id=>category.id,
                             :title=>article.title,
                             :slug=>article.slug,
                             :summary=>article.summary,
                             :content=>article.content}},
                    {:user_id => user.id}
    end

    #assert_redirected_to admin_posts_path(assigns(:posts))

  end

上面是我的功能测试代码,针对 postscontroller 的 create。 controller 中的代码是这样的。


def create
  @category = Category.find(params[:post][:category_id])

  params[:post].delete(:category_id)
  @post = @category.posts.build(params[:post])
  @post.user = current_user
  @post.tag_ids = params[:tag_ids]
  if @post.save
    flash[:notice] = "post was created successfully"
    redirect_to admin_posts_path
  else
    flash.now[:notice] = "create post failed"
    render :new
  end
end


create 成功之后会跳转,我在 chrome 的 developer tools 下面看到的也是一个 302,然后才是 200. 但是我的测试却提示我测试失败。

test_should_create_post_successfully(Admin::PostsControllerTest) [test/functional/admin/posts_controller_test.rb:22]:
Expected response to be a <:redirect>, but was <200>

有点不太明白,有明白人士帮忙解释一下。 @Rei @lgn21st

所以很可能是测试没通过,走到了 render :new 这一步

你把 @post.save 换成 @post.save! ,应该会抛出相应的错误。

是不是 @post.save 返回的是 false,save 失败了? 具体跟你的 Post 的 validator 有关。

#3 楼 @lgn21st #2 楼 @Rei @post.tag_ids = params[:tag_ids] 难道是这一行,我正在验证。

#3 楼 @lgn21st #2 楼 @Rei 已经证实,是 slug 的 validates 没有通过。原因是这一行。 article = FactoryGirl.create(:post_valid) create 就会在数据库中添加一行,所以在测试 post 的时候,又添加相同 slug 的 post,所以抛出异常了。 修改为 build,在不需要添加到数据库的时候,还是使用 build 较好一点。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号