在spec文件中使用create方法时,为什么ID为空?

时间:2011-11-04 23:19:22

标签: ruby-on-rails rspec

我在micropost_spec.rb中有以下代码:

  before(:each) do
    @user = Factory :user
    @attr = { :paragraphs => 4, :characters => 1000, :summary => "Recap of Event" }
  end

  it "should create a new instance given valid attributes" do
    @user.microposts.create!(@attr)
  end

当我运行测试时,我收到以下错误:

  Failure/Error: @user.microposts.create!(@attr)
  ActiveRecord::RecordInvalid:
     Validation failed: Id can't be blank

是否可以查看是否在rails控制台中设置了id?

1 个答案:

答案 0 :(得分:3)

您的模型可能正在尝试验证idvalidates_presence_of :id之类的validates :id, :presence => true。您不应该这样做,因为新记录的验证总是在记录保存到数据库并分配ID之前运行。