考虑以下代码:
class User {
static constraints = {
email email: true, unique: true
token nullable: true
}
String email
String password
String token
}@TestFor(User)
@TestMixin(DomainClassUnitTestMixin)
class UserSpec extends Specification {
def "email should be unique"() {
when: "twice same email"
def user = new User(email: "test@test.com", password: "test")
def user2 = new User(email: "test@test.com", password: "test")
then: "saving should fail"
user.save()
!user2.save(failOnError: false)
}
}使用以下配置(其中一部分),application.yml:
grails:
gorm:
failOnError: true
autoFlush: true为什么user2.save(failOnError: false)不返回false,因为它没有保存到数据库中?
运行输出:grails test-app *UserSpec
电子邮件应该是唯一失败的org.spockframework.runtime.ConditionNotSatisfiedError在UserSpec.groovy:40
当我用user.save()代替user.save(flush: true)时,它确实起作用了。
然而,https://grails.github.io/grails-doc/latest/guide/conf.html第4.1.3节的文档声称:
grails.gorm.autoFlush -如果设置为true,则导致合并、保存和删除方法刷新会话,替换使用保存显式刷新的需要(刷新: true)。
作为参考,这是grails --version的输出
Grails版本: 3.0.2 Groovy版本: 2.4.3 JVM版本: 1.8.0_40
这正是我在做的,我在这里错过了什么?
发布于 2015-07-29 22:45:59
我认为autoFlush文档具有误导性。
grails.gorm.autoFlush -如果设置为true,则导致合并、保存和删除方法刷新会话,替换使用保存显式刷新的需要(刷新: true)。
看看doSave()方法和GormInstanceApi ()。在doSave()的末尾,您将看到只有当刷新参数为真时会话才会被刷新:
if (params?.flush) {
session.flush()
}代码中没有任何东西表明刷新参数可以来自任何其他地方,而不是传递给保存()的内容。
我找不到证明它的代码,但我认为当Hibernate会话关闭时,例如当控制器或服务方法存在/返回时,autoFlush就会起作用。
另外,用于Spock和JUnit的GORM实现不是真正的GORM,所以它甚至可能不使用autoFlush配置。
我要在这里冒险。我还没有尝试过这种方法,但是您可能可以手动刷新会话。
@TestFor(User)
@TestMixin(DomainClassUnitTestMixin)
class UserSpec extends Specification {
def "email should be unique"() {
when: "twice same email"
def user = new User(email: "test@test.com", password: "test")
def user2 = new User(email: "test@test.com", password: "test")
simpleDatastore.currentSession.flush()
then: "saving should fail"
user.save()
!user2.save(failOnError: false)
}
}simpleDataStore来自DomainClassUnitTestMixin。
https://stackoverflow.com/questions/31049594
复制相似问题