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.
我一直在努力掌握编写测试的方法,但由于测试似乎从未像我希望的那样验证测试,因此遇到了很多麻烦。特别是,我一直在尝试使用Factory Girl而不是固定装置 - 正如我最近在网上看到的Railscasts和其他建议所示 - 由于它所宣称的好处,而且还没有成功。
For example, here is a simple Rspec test for a user model, testing to make sure a username is present...
例如,这是一个用户模型的简单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
And my factories.rb file, if it helps...
和我的factories.rb文件,如果它有帮助...
FactoryGirl.define do
factory :user do
sequence(:username) { |n| "registered-#{n}" }
password "foobar"
end
end
When I run 'rake spec,' it tells me...
当我运行'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
Ummm...that's the POINT. If I specified that the user should NOT be valid, shouldn't this test actually pass?
嗯......这就是POINT。如果我指定用户不应该有效,那么这个测试真的不应该通过吗?
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?
如果我替换Factory Girl行并在测试中将用户设置为'user = User.new(:username =>“”,:password =>“secret”)',那么测试通过就好了。那么为什么Factory Girl不能正常工作?
1 个解决方案
#1
22
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.
因为使用您正在使用的方法将尝试创建记录。有关详细信息,请参阅文档。
#1
22
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.
因为使用您正在使用的方法将尝试创建记录。有关详细信息,请参阅文档。