【发布时间】:2012-01-03 05:10:10
【问题描述】:
我一直在努力掌握如何编写测试,但遇到了很多麻烦,因为测试似乎从来没有按照我想要的方式验证。特别是,我一直在尝试使用 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")' 之类的东西,毫无疑问测试通过了。那么为什么工厂女孩不能正常工作呢?
【问题讨论】:
标签: ruby-on-rails rspec factory-bot