Ruby on rails rails中的单元测试问题,尤其是外键

Ruby on rails rails中的单元测试问题,尤其是外键,ruby-on-rails,unit-testing,Ruby On Rails,Unit Testing,我不能在rails中运行单元测试。我经常遇到这样的错误:SQLite3::ConstraintException:列电子邮件不是唯一的。我有一个外键为电子邮件在我的帖子模型,但我不知道为什么我不断得到上述错误。我的测试类代码如下所示: test "should not save post without title" do post = Post.new post.text = "hello world" assert !post.save end test "should not sa

我不能在rails中运行单元测试。我经常遇到这样的错误:SQLite3::ConstraintException:列电子邮件不是唯一的。我有一个外键为电子邮件在我的帖子模型,但我不知道为什么我不断得到上述错误。我的测试类代码如下所示:

test "should not save post without title" do
 post = Post.new
 post.text = "hello world"
 assert !post.save
end

test "should not save post without description" do
 post = Post.new
 post.title = "hello"
 assert !post.save
end

事实证明,rails 4不喜欢使用上述格式的测试。当我将方法头更改为以下内容时,它就起作用了:

  def test should_not_save_post_without_title
  //add testing code
  end
还要确保所有模型装置中都有需要测试的每个变量的样本数据。这方面的一个例子是:

在我的帖子中:

 one:
  text: MyString
  title: MyString

这应该是由你的电子邮件值引起的,检查你的数据库,你应该看到已经有一个空电子邮件记录。记住检查测试数据库而不是开发数据库。另外,请查看databasecleaner gem,以确保您的数据库在每次测试中都有一个干净的开始。