3

首先,我有一个有效的工厂/模型,并且这个特定的测试通过控制台运行良好。

模型

validate :some_condition

def some_condition
  errors.add(:attribute, "cannot be less than 5") if self.attribute < 5
end

测试

it "should not allow values above 5" do
  model = FactoryGirl.create(:model) # creates valid model
  model.attribute = 10
  model.valid?.should be_false
end

在控制台中:

model = FactoryGirl.create(:model)
model.attribute = 10
model.valid? # => false

在 rspec

undefined method `<' for nil:NilClass

我无法理解为什么会这样。这显然与self.attribute,但为什么它会在控制台中工作,而不是在测试中?attribute单独也返回相同的错误,我已经检查过 - self 被定义为模型实例。无论如何,这并不能解释这种不一致。它在控制台中工作,具有完全相同的模型和属性。

注意:我已经重新启动了所有环境,这是基于重新加载。

更新

无奈之下,我attribute在这个条件之前的几个上下文中输出了,然后exit。这带来了更奇怪的结果。解决这个问题:

def some_condition
  puts self.attribute # => returns blank in test, attribute value otherwise
  puts "#{self.attribute}" # => returns attribute value in test!!!
  exit

  errors.add(:attribute, "cannot be less than 5") if self.attribute < 5
end

以上让我无比紧张。我现在需要测试来测试我的测试吗?真的希望在 ruby​​ 或上述工具方面更有经验的人对这个烂摊子有一些合乎逻辑的解释,因为我完全迷路了。

它导致了这种可憎:

errors.add(:attribute, "cannot be less than 5") if self.attribute < 5
# => IN TESTS self.attribute returns nil

errors.add(:attribute, "cannot be less than 5") if "#{self.attribute}".to_i < 5
# => IN TESTS self.attribute returns value! This works!?

你甚至转向哪里?是 ruby​​、rails、factory girl、rspec 吗?

使固定

在一个问题的大量破坏之后,事实证明我rake db:test:prepare在一次小的迁移之后忘记了。我仍然对它如何导致这样的问题感到困惑。学过的知识。跨环境运行迁移,并找到更好的调试器!

4

1 回答 1

0

RSpec 语法从版本 1 到版本 2 发生了一些变化,这可能会使事情变得混乱。

你能告诉我如果你完全像这样写你的测试会发生什么吗?

it "should not allow values above 5" do
  model = build(:model, :attribute => 10)
  model.should_not be_valid
  model.should have(1).error_on(:attribute)
end

我使用build而不是create这样的原因是您可以在不访问数据库的情况下测试您的验证。

于 2013-01-29T00:37:49.207 回答