Validation fails even though content is NOT blank in specs
I am learning Rails using the RailsTutorial screencasts by Michael Hartl. When I included the validations on the user model as per Listing 11.14, I got the error
Micropost should create a new instance with valid attributes
开发者_StackOverflow Failure/Error: @user.microposts.create!(@attr)
Validation failed: Content can't be blank
# ./spec/models/micropost_spec.rb:10:in `block (2 levels) in <top (required)>'
I would appreciate any help from the community in figuring this out. Thank you.
Here's micropost_spec
require 'spec_helper'
describe Micropost do
before(:each) do
@user = Factory(:user)
@attr = Micropost.new(:content => "value for content")
end
it "should create a new instance with valid attributes" do
@user.microposts.create!(@attr)
end
describe "user associations" do
before(:each) do
@micropost = @user.microposts.create(@attr)
end
it "should have a user attribute" do
@micropost.should respond_to(:user)
end
it "should have the right associated user" do
@micropost.user_id.should == @user.id
@micropost.user.should == @user
end
end
describe "validations" do
it "should have a user id" do
Micropost.new(@attr).should_not be_valid
end
it "should require non-blank content" do
@user.microposts.build(:content => " ").should_not be_valid
end
it "should reject long content" do
@user.microposts.build(:content => "a"*141).should_not be_valid
end
end
end
Here's the micropost model micropost.rb
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 140 }
validates :user_id, :presence => true
default_scope :order => 'microposts.created_at DESC'
end
Use this:
before(:each) do
@user = Factory(:user)
@attr = { :content => "value for content" }
end
it "should create a new instance with valid attributes" do
@user.microposts.create!(@attr)
end
@user.microposts.create!
method expects a Hash of attributes, not an instantiated Class.
It appears you're passing a model instance when you instead want an attribute hash (this can be confusing).
精彩评论