Ruby on rails 铁路及;是否应该进行规格匹配:验证(:名字)爆炸的存在性

Ruby on rails 铁路及;是否应该进行规格匹配:验证(:名字)爆炸的存在性,ruby-on-rails,rspec,shoulda,Ruby On Rails,Rspec,Shoulda,很好。但我要补充一点: 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 valida

很好。但我要补充一点:

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)}
对于,没有将nil隐式转换为字符串+


如何解决此问题?

看起来您的
名字和
姓氏在测试中是
nil
。 尝试在
块之前的
中存根值,如下所示:

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

这就是(:first\u name)
验证的工作原理:

  • 它将
    nil
    分配给模型的
    first\u name
    属性,并在模型上调用
    .valid?
  • 如果
    .valid?
    返回true-测试失败,因为如果您有正确的验证,就不会发生这种情况
  • 我假设
    get\u url
    方法设置为在
    上运行,然后再进行验证
    回调,那么代码中发生了什么:

  • first\u name
    被分配给
    nil
  • 调用
    .valid?
  • 在\u验证之前
    回调触发您的
    get\u url
    方法
  • 一切都爆炸了,因为
    get\u url
    没有考虑到
    first\u name
    可以是
    nil
  • 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