【问题标题】:rspec model testing in rails: method works but test wont passrails中的rspec模型测试:方法有效,但测试不会通过
【发布时间】:2012-09-01 04:07:19
【问题描述】:

我有两个模型 Indicator belongs_to Privacy。

在指标中我写了一个方法来返回隐私设置的正确名称

def privacy
    Privacy.find(privacy_tag_id).content
end

这适用于 rails 控制台。如果我创建一个指标然后运行 ​​Indicator.privacy 我会返回“红色”或“绿色”或其他任何内容。但我无法让我的 rspec 通过。这是测试

describe "indicator" do
    it "should return a human named when asked for its privacy level" do
        @privacy = PrivacyTag.create(:content => "Secret")
        @ind = Indicator.new(:content => 'test',
                             :privacy_tag_id => @privacy.id)
        @ind.privacy.should == "Secret"
    end
end

当我运行测试时,我收到以下消息:

Failures:

  1) indicator should return a human named when asked for its privacy level
     Failure/Error: @ind.privacy.should_equal "Secret"
     ActiveRecord::RecordNotFound:
       Couldn't find PrivacyTag without an ID
     # ./app/models/indicator.rb:13:in `privacy'
     # ./spec/models/indicator_model_spec.rb:9:in `block (2 levels) in <top (required)>'

我在测试中做错了什么?有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails testing rspec


    【解决方案1】:

    我怀疑Privacy 对象没有被创建。尝试调用create! 而不是create。如果它引发异常,则意味着您的 Privacy 模型中有一些验证。

    首先看到您的模型会非常有帮助。

    【讨论】:

    • 很好的验证电话。这正是问题所在。很抱歉不包括模型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多