我刚开始使用RSpec和一个新项目(在成为最小的用户一段时间之后)。我创建了一个名为contract的MVC。这是模型文件:
class Contract < ActiveRecord::Base
attr_accessible :name, :number, :plannedStart, :actualStart, :plannedCompletion, :actualCompletion
end
我有一个为Contracts定义的基本工厂(之前稍微复杂一点,使用序列生成新的名称和数字,但我删除了所有这些以尝试简化压缩此错误):
FactoryGirl.define do
factory :contract do
end
end
以下是规格(几乎是自动生成的,除了我在工厂的调用中添加的内容):
require File.dirname(__FILE__) + '/../spec_helper'
describe ContractsController do
render_views
it "index action should render index template" do
create(:contract)
get :index
response.should render_template(:index)
end
it "show action should render show template" do
create(:contract)
get :show, :id => Contract.first
response.should render_template(:show)
end
it "new action should render new template" do
get :new
response.should render_template(:new)
end
it "create action should render new template when model is invalid" do
Contract.any_instance.stubs(:valid?).returns(false)
post :create
response.should render_template(:new)
end
it "create action should redirect when model is valid" do
Contract.any_instance.stubs(:valid?).returns(true)
post :create
response.should redirect_to(contract_url(assigns[:contract]))
end
it "edit action should render edit template" do
create(:contract)
get :edit, :id => Contract.first
response.should render_template(:edit)
end
it "update action should render edit template when model is invalid" do
create(:contract)
Contract.any_instance.stubs(:valid?).returns(false)
put :update, :id => Contract.first
response.should render_template(:edit)
end
it "update action should redirect when model is valid" do
create(:contract)
create(:contract)
Contract.any_instance.stubs(:valid?).returns(true)
put :update, :id => Contract.first
response.should redirect_to(contract_url(assigns[:contract]))
end
it "destroy action should destroy model and redirect to index action" do
create(:contract)
contract = Contract.first
delete :destroy, :id => contract
response.should redirect_to(contracts_url)
Contract.exists?(contract.id).should be_false
end
end
当我运行规范时,我收到以下错误消息,但是我得到的数量因运行而异:
ActiveRecord::RecordInvalid: Validation failed:
./spec/controllers/contracts_controller_spec.rb:39:in `block (2 levels) in <top (required)>'
ActiveRecord::RecordInvalid: Validation failed:
./spec/controllers/contracts_controller_spec.rb:45:in `block (2 levels) in <top (required)>'
ActiveRecord::RecordInvalid: Validation failed:
./spec/controllers/contracts_controller_spec.rb:7:in `block (2 levels) in <top (required)>'
10 examples, 3 failures, 7 passed
Finished in 0.360139 seconds
/Users/jlee/.rvm/rubies/ruby-1.9.3-p194/bin/ruby -S rspec ./spec/controllers/contracts_controller_spec.rb ./spec/models/contract_spec.rb failed
我已经实现了Databasecleaner,以确保这不是一些与测试期间使用事务相关的奇怪行为问题,但无济于事。建议?我没有定义任何验证,因此很难理解我如何验证失败。
答案 0 :(得分:0)
存根:有效吗?在测试之间徘徊,所以我将以下内容放在before(:each)块中:Contract.any_instance.unstub(:valid?),它清除了所有内容。