【问题标题】:Rails & Shoulda Spec Matcher: validate_presence_of (:first_name) blowing upRails & Shoulda Spec Matcher: validate_presence_of (:first_name) 爆炸
【发布时间】:2015-09-19 01:40:55
【问题描述】:
describe User do

  it { should belong_to(:shop) }


  it { should respond_to(:shop) }
  it { should respond_to (:first_name)}
  it { should respond_to (:last_name)}
  it { should respond_to (:email)}

工作正常。但只要我添加:

it { should validate_presence_of (:first_name)}
it { should validate_presence_of (:last_name)}

它坏了,特别是在这个回调方法中:

def get_url
    source = "http://www.randomsite.com/"+ first_name + "+" + last_name
end

对于 + 没有将 nil 隐式转换为字符串

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    看起来您的 first_namelast_name 是用于测试的 nil。 尝试像这样将 before 块中的值存根:

    context 'first_name and last_name validation' do
      before do
        allow(subject).to receive(:first_name).and_return('bob')
        allow(subject).to receive(:last_name).and_return('tom')
      end
    
      it { should validate_presence_of (:first_name)}
      it { should validate_presence_of (:last_name)}
    end
    

    【讨论】:

      【解决方案2】:

      嗯,这就是validate_presence_of(:first_name) 的工作原理:

      1. 它将nil 分配给模型的first_name 属性,并在模型上调用.valid?
      2. 如果 .valid? 返回 true - 测试失败,因为如果您进行了正确的验证,那将不会发生。

      我假设get_url 方法设置为在before_validation 回调上运行,那么您的代码中发生了什么:

      1. first_name 被分配给 nil
      2. .valid? 被调用。
      3. before_validation 回调触发您的 get_url 方法
      4. 一切都炸了,因为get_url 没有考虑到first_name 可以是nil

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-13
        • 1970-01-01
        • 2011-10-05
        相关资源
        最近更新 更多