我的控制器规格失败,因为Factory Girl似乎正在创建非唯一用户,即使我对需要唯一的用户属性进行排序。
错误
1) TopicsController POST #create when topic is invalid should render new
Failure/Error: let(:invalid_topic) {Factory.build :invalid_topic}
ActiveRecord::RecordInvalid:Validation failed: Email has already been taken, Username has already been taken
2) TopicsController POST #create when topic is valid should redirect to show
Failure/Error: let(:valid_topic) {Factory.build :topic}
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Username has already been taken
控制器规格(RSpec)
describe "POST #create" do
let(:valid_topic) {Factory.build :topic}
let(:invalid_topic) {Factory.build :invalid_topic}
context "when topic is invalid" do
it "should render new" do
post :create, :topic => invalid_topic
response.should render_template(:new)
end
end
context "when topic is valid" do
it "should redirect to show" do
post :create, :topic => valid_topic
response.should redirect_to(topic_path(assigns(:topic)))
end
end
end
工厂
Factory.define :user do |f|
f.sequence(:username) { |n| "foo#{n}"}
f.password "password"
f.password_confirmation { |u| u.password}
f.sequence(:email) { |n| "foo#{n}@example.com"}
end
Factory.define :topic do |f|
f.name "test topic"
f.association :creator, :factory => :user
f.forum_id 1
end
当我使用Factory.create :topic
时,为什么Factory Girl不对用户属性进行排序?
答案 0 :(得分:29)
rake db:test:prepare
似乎解决了这个问题。
不知道为什么。架构尚未更改。
答案 1 :(得分:4)
请考虑使用database_cleaner gem。其中一个专门用于实现在测试运行之间清理数据库的目的。
This post几乎解释了一切。
答案 2 :(得分:3)
您应该考虑在测试结束时手动删除所有主题。当然,它不是第一解决方案,但对我来说真的很棒。
after(:all) { Topic.delete_all }