我正在使用 RSpec 进行测试,但我不知道如何将其变为绿色。
在这种情况下,我有一个名为“PartType”的模型,它包含一个名为“quotation”的属性。
quotation 的值来自表单,因此它将是一个字符串。
为了演示,您可以转到控制台并输入:
(1..1000).includes?("50") # false
但是..
(1..1000).includes?(50) # true
并且这个值可以有小数。所以我需要做一个“type_cast”。
我的 PartType
模型上有这个:
before_validation :fix_quotation, :if => :quotation_changed?
protected
def fix_quotation
self[:quotation] = quotation_before_type_cast.tr(' $, ' , '.' )
end
这按预期工作,但在进行测试时,它失败了。
这是我的part_type_spec.rb
:
require 'spec_helper'
describe PartType do
before(:each) do
@attr = { :title => "Silver", :quotation => 100 }
end
it "should create a instance given a valid attributes" do
PartType.create!(@attr)
end
it "should accept null value for quotation" do
PartType.new(@attr.merge(:quotation => nil)).should be_valid
end
it "should accept 0 value for quotation" do
PartType.new(@attr.merge(:quotation => 0)).should be_valid
end
end
最后是失败的测试:
Failures:
1) PartType 应该创建一个给定有效属性的实例
失败/错误:PartType.create!(@attr)
没有方法错误:
未定义的方法 tr' for 100:Fixnum
# ./app/models/part_type.rb:7:in
fix_quotation'
# ./spec/models/part_type_spec.rb:10:in `block (2 levels) in '
2) PartType 应该接受 0 值进行报价
失败/错误:PartType.new(@attr.merge(:quotation => 0)).should be_valid
没有方法错误:
未定义的方法 tr' for 0:Fixnum
# ./app/models/part_type.rb:7:in
fix_quotation'
# ./spec/models/part_type_spec.rb:18:in `block (2 levels) in '
在 0.06089 秒内完成 3个例子,2个失败
最佳答案
- 你的
include?
片段是错误的,我第一个错误,第二个正确。 before_validation
被执行并且quotation_before_type_cast
应该是一个String
但它是一个Fixnum
。将100
更改为'100'
,将0
更改为'0'
。
关于ruby-on-rails - 测试没有通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7157131/