我有一个ActiveRecord模型:
class Hotlink < ActiveRecord::Base
validates_presence_of :link
end
我测试:
require 'spec_helper'
describe Hotlink do
it "should require a name" do
Hotlink.new.should_not be_valid
end
it "should require a name 2" do
link1 = Hotlink.new
link1.link = nil
link1.should_not be_valid
end
it "should require a name 3" do
link2 = Hotlink.new
link2.link = nil
link2.save
link2.should_not be_valid
link2.valid?.should be_false
end
end
所有这些测试都失败了。我糊涂了?这些不能通过吗?
他们失败了:预期有效吗?返回false,得到了真实
在environment / test.r中我没有运气就关闭了缓存分类。
编辑:以下作品。我现在更加困惑:
Hotlink.new().valid?.should != true
编辑:找到问题的来源:
我有一个控制器规格,如果我删除将使模型规格通过。这是为什么?
require File.dirname(__FILE__) + 'spec_helper'
describe HotlinksController do
before :each do
@current_user = mock_model(User, :id => 1)
controller.stub!(:current_user).and_return(@current_user)
controller.stub!(:login_required).and_return(:true)
end
fixtures :all
render_views
it "create action should redirect when model is valid" do
Hotlink.any_instance.stubs(:valid?).returns(true)
post :create
response.should redirect_to(root_url)
end
end
答案 0 :(得分:0)
我指着这条线:
Hotlink.any_instance.stubs(:valid?).returns(true)
我喜欢一个合适的解决办法,但是当我不久前碰到这样的事情时,我找到了一种测试所需行为的方法,而没有麻烦的模拟。
在这种情况下,你可能会逃避(未经测试):
hotlink = Hotlink.new
Hotlink.stub(:new).and_return(hotlink)
hotlink.stub(:valid?).and_return(true)