我在使用 rspec + factory-girl 时遇到了一些困难。刚刚开始,这是我的代码示例:
工厂/用户.rb
require 'faker'
FactoryGirl.define do
factory :user do |f|
f.email { Faker::Internet.email }
f.password "SamplePassword"
end
end
工厂/收藏夹.rb
FactoryGirl.define do
factory :favourite do
# `ex_products` table is an external sqlserver table
# and it can't be tested with factories cause
# there is just one production instance of it.
ex_product_id 50136
user
end
end
规格/模型/favourite_spec.rb
require 'spec_helper'
describe Favourite do
subject(:favourite) { FactoryGirl.build(:favourite) }
it { expect(favourite).to be_valid }
it "is invalid without a user" do
favourite.user = nil
expect(favourite).to be_invalid
end
it "is invalid without a product" do
favourite.ex_product = nil
expect(favourite).to be_invalid
end
describe "#toggle_for_user" do
context "when product is faved" do
before(:all) do
FactoryGirl.create(:favourite)
end
it "removes it from favourites" do
product = favourite.ex_product
user = favourite.user
Favourite.toggle_for_user(product, user)
expect(Favourite.all).to be_nil
end
end
context "when product is not faved" do
it "adds it to favourites"
end
end
end
现在,问题是:当我在测试#toggle_for_user / "removes it from favourites"
部分时,我的测试数据库中有两条User
记录,这导致我的测试因用户模型验证和此处未提及的关系而失败。但是,它们并不重要,我唯一需要知道的是为什么舞台上的数据库中有两条User
记录,removes it from favourites
我能用它做什么。我在 factory_girl 文档中找不到任何关于它的信息。
我用来运行这个测试的命令是:
rspec 规格/模型/favourite_spec.rb
所以这是唯一触发的测试。
在此先感谢您提供任何线索!