【发布时间】:2016-04-29 09:57:15
【问题描述】:
我正在编写一个名为 Leads 控制器规范的 RSpec。在那我正在编写一个测试来创建铅控制器的动作。现在我的领导控制器调用项目模型来创建一个对象(项目),该对象还创建联系人对象并将其分配给项目。但是当我尝试测试我的项目模型是否创建了联系人对象时,测试失败了。我不知道为什么我的联系人对象没有被创建:(
我的leads_controller_spec.rb
describe "POST #create" do
it "should create a contact too" do
my_lead = Fabricate(:project, id: Faker::Number.number(10))
expect{
post :create, project: my_lead.attributes
}.to change(Contact, :count).by(1)
end
it "should be equal to last created contact" do
my_lead = Fabricate(:project, id: Faker::Number.number(10))
post :create, project: my_lead.attributes
expect(Project.last.contact).to eq(Contact.last)
end
end
leads_controller.rb
def create
if @lead = Project.add_new_lead(lead_params)
@lead.create_activity :create_new_lead, owner: current_user
puts "My lead in create action: #{@lead.inspect}"
else
respond_to do |format|
format.html { redirect_to :back, :alert => "Email is already Taken"}
end
end
respond_to do |format|
format.html { redirect_to leads_path }
end
end
项目.rb
def add_new_lead(inputs, data = {})
if !Contact.where(email: inputs[:email]).present?
contact = Contact.create(phone: inputs[:phone], email: inputs[:email], fullname: inputs[:fullname])
project = Project.create(name: inputs[:fullname], flat_status: inputs[:flat_status], flat_type: inputs[:flat_type], flat_area: inputs[:area], location: inputs[:locality], address: inputs[:site_address], customer_type: inputs[:customer_type])
project.contact = contact
project.save
project
else
return nil
end
end
contact_fabricator.rb
require 'faker'
Fabricator(:contact) do
email { "email_#{Kernel.rand(1..30000)}@prestotest.com" }
fullname "project#{Kernel.rand(1..30000)}"
address "address#{Kernel.rand(1..30000)}"
end
project_fabricator.rb
require 'faker'
Fabricator(:project) do
contact
end
联系人.rb
field :phone, type: String
field :email, type: String
field :fullname, type: String
field :status, type: String, default: "DEFAULT"
field :address, type: String
field :new_address, type: String
field :other_data, type: Hash, default: {}
validates_presence_of :email
validates_uniqueness_of :email, :message => "Email already taken"
【问题讨论】:
-
失败消息:预期 #count 已更改 1,但已更改 0
-
是否有可能您的测试没有创建新的
Contact,因为数据库中已经存在匹配的联系人或验证失败?您是否在两次运行测试套件之间删除数据库?你的Contact模型有验证吗? -
是的 spickermann 我确实对 Contact 模型进行了验证,您可以看到 Contact.rb 文件的最后两行。但是如果我删除验证,那么测试将变为绿色,但我仍然需要验证。
-
我在两次测试套件运行之间清理了我的数据库
标签: ruby-on-rails ruby mongodb rspec mongoid