即使内容在规范中不是空白,验证也会失败

时间:2011-01-26 18:20:01

标签: ruby-on-rails ruby-on-rails-3 error-handling

我正在使用Michael Hartl的RailsTutorial截屏视频学习Rails。当我按照清单11.14 在用户模型中包含验证时,我收到了错误

 Micropost should create a new instance with valid attributes
 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)>'

我希望社区能够帮助您解决这个问题。谢谢。

这是 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

这是微博模型 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

2 个答案:

答案 0 :(得分:3)

使用此:

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!方法需要哈希属性,而不是实例化的类。

答案 1 :(得分:1)

当你想要一个属性哈希时,你似乎正在传递一个模型实例(这可能会令人困惑)。

相关问题