首先,我有一个有效的工厂/模型,这个特定的测试通过控制台运行良好。
型号
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
有关,但为什么在console能用,在tests却不行呢? 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
。我仍然对它如何导致这样的问题感到困惑。学过的知识。跨环境运行迁移,并找到更好的调试器!
最佳答案
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
的原因是您可以在不访问数据库的情况下测试验证。
关于ruby-on-rails - Rspec/Guard/FactoryGirl 返回错误 'undefined method' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14573088/