Sha*_*non 18 rspec ruby-on-rails factory-bot
我一直在努力掌握编写测试的方法,但是由于测试似乎永远无法验证我想要的方式,因此我遇到了很多麻烦.特别是,我一直在尝试使用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
Run Code Online (Sandbox Code Playgroud)
和我的factories.rb文件,如果它有帮助...
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "registered-#{n}" }
password "foobar"
end
end
Run Code Online (Sandbox Code Playgroud)
当我运行'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
Run Code Online (Sandbox Code Playgroud)
嗯......这就是POINT.如果我指定用户不应该有效,那么这个测试真的不应该通过吗?
如果我更换了Factory Girl系列并在测试中设置了类似的用户'user = User.new(:username => "", :password => "secret")'
,毫不奇怪,测试通过正常.那么为什么Factory Girl不能正常工作?
luc*_*tte 22
您应该使用如下所示的构建:
user = Factory.build(:user, :username=>"foo")
Run Code Online (Sandbox Code Playgroud)
因为使用您正在使用的方法将尝试创建记录.有关详细信息,请参阅文档.