【问题标题】:Tests are not passing测试未通过
【发布时间】:2011-08-23 15:06:15
【问题描述】:

我正在使用 RSpec 进行测试,但我不知道如何将其变为绿色。

在这种情况下,我有一个名为“PartType”的模型,它包含一个名为“quotation”的属性。

引用的值来自一个表单,所以它是一个字符串。

为了演示,您可以转到控制台并输入:

(1..1000).includes?("50") # false

但是..

(1..1000).includes?(50) # true

而且这个值可以有小数。所以我需要做一个“type_cast”。

我的PartTypemodel 上有这个:

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:infix_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:infix_quotation' # ./spec/models/part_type_spec.rb:18:in `block (2 levels) in '

在 0.06089 秒内完成 3个例子,2个失败

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 testing rspec


    【解决方案1】:
    1. 你的include?sn-ps 错了,我第一个是假的,第二个是真的。
    2. before_validation 被执行,quotation_before_type_cast 应该是 String 但它是 Fixnum。将100 更改为'100',将0 更改为'0'

    【讨论】:

    • 编辑了 sn-ps,谢谢。我是否总是必须将值作为字符串引用?甚至我希望它是一个整数值?
    • 是的,因为您希望它们成为before_validation 方法中的字符串。
    猜你喜欢
    • 2020-08-08
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多