Factory Girl 未通过 Rspec 验证测试

发布于 2024-12-17 12:53:17 字数 1079 浏览 1 评论 0原文

我一直在尝试掌握编写测试的方法,但是遇到了很多麻烦,因为测试似乎从未按照我想要的方式进行验证。特别是,我一直在尝试使用 Factory Girl 而不是固定装置 - 正如最近的 Railscasts 和我在网上看到的其他建议所建议的那样 - 由于它声称有好处,但这还没有成功。

例如,这是一个针对用户模型的简单 Rspec 测试,测试以确保用户名存在...

describe User do
  it "should not be valid without a username" do
    user = FactoryGirl.create(:user, :username => "", :password => "secret")
    user.should_not be_valid
  end
end

以及我的factory.rb 文件,如果它有帮助...

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "registered-#{n}" }
    password "foobar"
  end
end

当我运行“rake spec”时,它会告诉我。 ..

1) User should not be valid without a username
     Failure/Error: user = FactoryGirl.create(:user, :username => "", :password => "secret")
     ActiveRecord::RecordInvalid:
       Validation failed: Username can't be blank

嗯...这就是重点。如果我指定用户不应该是有效的,那么这个测试是否应该真正通过?

如果我替换 Factory Girl 行并在测试中设置用户,例如 'user = User.new(:username => "", :password => "secret")',毫不奇怪,测试顺利通过。那么为什么工厂女孩工作不正常呢?

I've been trying to get a grasp on writing tests, but having a lot of trouble as the tests never seem to validate the way I want them to. In particular, I've been trying to use Factory Girl as opposed to fixtures - as suggested by a recent Railscasts and other advice I've seen on the net - due to the benefits it professes, and that hasn't worked out.

For example, here is a simple Rspec test for a user model, testing to make sure a username is present...

describe User do
  it "should not be valid without a username" do
    user = FactoryGirl.create(:user, :username => "", :password => "secret")
    user.should_not be_valid
  end
end

And my factories.rb file, if it helps...

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "registered-#{n}" }
    password "foobar"
  end
end

When I run 'rake spec,' it tells me...

1) User should not be valid without a username
     Failure/Error: user = FactoryGirl.create(:user, :username => "", :password => "secret")
     ActiveRecord::RecordInvalid:
       Validation failed: Username can't be blank

Ummm...that's the POINT. If I specified that the user should NOT be valid, shouldn't this test actually pass?

If I replace the Factory Girl line and set the user in the test with something like 'user = User.new(:username => "", :password => "secret")', to no surprise the test passes fine. So why is Factory Girl not working right?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

回眸一笑 2024-12-24 12:53:17

您应该使用如下所示的构建:

user = Factory.build(:user, :username=>"foo")

因为使用您正在使用的方法将尝试创建一条记录。有关更多信息,请参阅文档

You should use build like in the following:

user = Factory.build(:user, :username=>"foo")

Because using the method you're using will try to create a record. See docs for further information.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文