我在spec / requests中有类似的代码:
describe "with valid data" do
let(:player) { FactoryGirl.create :player }
let(:player2) { FactoryGirl.create :player2 }
@player = Player.new(firstname: "Tom", lastname: "Greg", nickname: "jimi21")
@player.save
@players = Player.all
p @players.count
end
控制台中的输出是:
1
为什么此代码不在测试数据库中创建对象?我的意思是这一行:
let(:player) { FactoryGirl.create :player }
我想根据保存在DB中的玩家编写更多测试。 如何使用RSpec和FactoryGirl巧妙地做到这一点?
FactoryGirl文件中的代码:
FactoryGirl.define do
factory :player do
firstname "John"
lastname "Smith"
nickname "smithy99"
avatar { File.new(Rails.root.join('spec/images/1.png')) }
end
factory :player2 do
firstname "Tom"
lastname "Marlow"
nickname "marlowy11"
avatar { File.new(Rails.root.join('spec/images/1.png')) }
end
end
答案 0 :(得分:2)
您的代码中实际上没有任何测试,并且您永远不会引用您在其中设置的变量,因此您的let
块永远不会被运行。
RSpec中的测试包含在it
块中,例如
it "tests something" do
# This is a test! player will be defined here!
end
如果您设置了这样的测试,并在其中引用player
和player2
,则会定义它们。
如果您不希望手动引用它们来定义它们,您可能希望使用let!
代替let
急切加载它们。
要获得完整的代码片段,我会根据自己的需要进行操作:
describe "with valid data" do
let!(:player) { FactoryGirl.create :player }
let!(:player2) { FactoryGirl.create :player2 }
it "doesn't allow duplicate names" do
@player = Player.new(firstname: "Tom", lastname: "Greg", nickname: "jimi21")
@player.save
@players = Player.all
p @players.count
end
end