测试中的验证错误但错误数组为空

时间:2012-02-07 18:05:18

标签: validation testing activerecord ruby-on-rails-3.1

我有这个代码用于创建主题并在Rails 3.1中的论坛应用程序中发布:

def create
  @topic = Topic.new(:name => params[:topic][:name], :last_post_at => Time.now)
  @topic.forum_id = params[:topic][:forum_id]
  @topic.user = current_user

  if @topic.save
    @post = Post.new(:content => params[:post][:content])
    @post.topic = @topic
    @post.user = current_user

    @post.save!
    ...

通过相应的表单发布到create方法时,会创建主题和帖子,并且两个save调用都会成功。

当我通过功能测试调用create方法时,主题会被保存,但帖子有验证错误。

ActiveRecord::RecordInvalid: Validation failed: 
app/controllers/topics_controller.rb:23:in `create'
test/functional/topics_controller_test.rb:26:in `block in <class:TopicsControllerTest>'

测试如下:

test "should create topic" do
  post :create, :topic => {:name => "New topic", :forum_id => forums(:one).id}, :post => {:content => "Post content"}
end

current_user通过设置方法登录。)

当我通过调试器或@post.errors.full_messages显示post对象的错误时,错误数组为空。

Post模型如下所示:

class Post < ActiveRecord::Base
  attr_accessible :content

  belongs_to :topic
  belongs_to :user
end

Topic模型:

class Topic < ActiveRecord::Base
  belongs_to :user
  belongs_to :last_poster, class_name: 'User'

  attr_accessible :name, :last_poster_id, :last_post_at

  belongs_to :forum
  has_many :posts, :dependent => :destroy
end

如何找出导致验证错误的原因?

1 个答案:

答案 0 :(得分:0)

问题是我在测试失败之前执行的测试中使用了mocha的Post.any_instance.stubs(:valid?).returns(false)

显然,您必须先恢复原始行为,然后再致电Post.any_instance.unstub(:valid?)继续进行其他测试。