简体   繁体   English

使用Shoulda(而不是rspec)在Rails项目中的范围内测试唯一性

[英]Testing uniqueness in a scope in a Rails project using shoulda (but not rspec)

I have a user class with an email that is unique but scoped to the tenant: 我有一个用户类,其中的电子邮件是唯一的,但范围仅限于租户:

class User < ActiveRecord::Base
  validates :email, :uniqueness => {:scope => :tenant_id, :allow_blank => true}
  #...
end

I'm trying to test it with: 我正在尝试使用:

class UserTest < ActiveSupport::TestCase
  context "a user" do
    setup { @user = create :user }
    subject { @user }

    should validate_uniqueness_of(:email).scoped_to(:tenant_id)
  end
end

but the test fails with this message: 但测试失败并显示以下消息:

Expected errors to include "has already been taken" when email is set to "joseph.allen_1@example.com", got errors: ["email has already been taken (\\"joseph.allen_1@example.com\\")", "first_name can't be blank (nil)", "last_name can't be blank (nil)"] (with different value of tenant_id) 当电子邮件设置为“ joseph.allen_1@example.com”时,预期的错误包括“已被接收”,出现错误:[“电子邮件已被接收(\\“ joseph.allen_1@example.com \\”)“, “ first_name不能为空(nil)”,“ last_name不能为空(nil)”](具有不同的tenant_id值)

which raises many questions. 这引起了很多问题。 Why is the error message not matching? 为什么错误消息不匹配? It seems because the actual email address is included in the error message, but why is it included? 似乎是因为错误消息中包含了实际的电子邮件地址,但是为什么要包含它? When I generate the error from the UI it doesn't seem to be included: 当我从用户界面生成错误时,似乎未包含该错误:

在此处输入图片说明

Also, at the end it says that it's trying it with a different tenant, which if it was true, it shouldn't generate any error (it doesn't when I run the app itself), but, why is it expecting the error? 此外,最后它说它正在与其他租户一起尝试,如果为真,则它不会产生任何错误(当我运行应用程序本身时不会发生任何错误),但是,为什么它会期待错误? It should only expect the error if it's the same tenant_id. 如果它是相同的tenant_id,则应该仅预期错误。

This is so confusing. 这真令人困惑。 Any ideas what's going on and/or how to properly test this? 有任何想法怎么回事和/或如何正确测试吗?

Just ran into this same issue. 刚遇到同样的问题。 We were able to resolve it by changing 我们能够通过更改解决它

should validate_uniqueness_of(:email).scoped_to(:tenant_id)

to

should validate_uniqueness_of(:email_id).scoped_to(:tenant_id)

Don't know if it's exactly the same situation, but apparently our issue was caused by nested resources throwing the matcher for a loop somehow. 不知道这是否完全相同,但是显然我们的问题是由嵌套资源以某种方式将匹配器抛出循环引起的。

I find that the scoped_to has obscure issues with certain tests. 我发现scoped_to在某些测试中存在晦涩的问题。 Whenever encountered, it becomes necessary to write more verbose tests and manually test the failure to create an object in the same scope. 无论何时遇到,都有必要编写更多详细的测试并手动测试在相同范围内创建对象的失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM