我在使用rspec + factory-girl时遇到了一些困难。刚开始,这是我的代码示例:
require 'faker'
FactoryGirl.define do
factory :user do |f|
f.email { Faker::Internet.email }
f.password "SamplePassword"
end
end
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
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 docs中找不到任何相关内容。
我用来运行此测试的命令是:
rspec spec / models / favourite_spec.rb
所以这是唯一的测试。
提前感谢任何线索!
答案 0 :(得分:3)
subject(:favourite) { FactoryGirl.build(:favourite) }
此行构建并保存User实例和构建,但默认情况下不保存Favorite对象。检查“关联”标题下方的the docs。猜猜strategy: :build
可以帮助您。