Factory Girl 未通过 Rspec 验证测试
我一直在尝试掌握编写测试的方法,但是遇到了很多麻烦,因为测试似乎从未按照我想要的方式进行验证。特别是,我一直在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用如下所示的构建:
因为使用您正在使用的方法将尝试创建一条记录。有关更多信息,请参阅文档。
You should use build like in the following:
Because using the method you're using will try to create a record. See docs for further information.