I have this code for creating a topic and post in a forum application in 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!
...
When posting to the create method via the corresponding form, the topic and the post are created and both save calls are successful.
When I call the create method via a functional test, the topic is saved but the post has validation errors.
ActiveRecord::RecordInvalid: Validation failed:
app/controllers/topics_controller.rb:23:in `create'
test/functional/topics_controller_test.rb:26:in `block in <class:TopicsControllerTest>'
The test looks like this:
test "should create topic" do
post :create, :topic => {:name => "New topic", :forum_id => forums(:one).id}, :post => {:content => "Post content"}
end
(current_user is logged in via a setup method.)
When I display the errors of the post object via the debugger or with @post.errors.full_messages, the error array is empty.
The Post model looks like this:
class Post < ActiveRecord::Base
attr_accessible :content
belongs_to :topic
belongs_to :user
end
And the Topic model:
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
How can I find out what is causing the validation error?
The problem was that I used mocha’s
Post.any_instance.stubs(:valid?).returns(false)in a test that was executed before my failing test.Apparently, you have to restore the original behavior before proceeding with other tests by calling
Post.any_instance.unstub(:valid?).