Rspec存根不能使用before_create回调

时间:2015-03-27 16:16:11

标签: ruby-on-rails rspec stubbing

这是我的测试:

it "should have shortened links that when clicked, redirect me back to the
      original url" do
      allow_any_instance_of(Link).to receive(:shorten_url).and_return("bit.ly-remix/11111111")
      link = build(:link, orig_url: "https://www.google.com/search?q=balut+egg&espv=2&biw=1280&bih=678&source=lnms&tbm=isch&sa=X&ei=CngVVanlMIG5ogSap4GQDQ&ved=0CAYQ_AUoAQ#imgdii=_&imgrc=qnYT21R-r5VDRM%253A%3BIbuD8fXhkqTEDM%3Bhttp%253A%252F%252Fwww.bizarrefood.com%252Fblog%252Fwp-content%252Fuploads%252F2012%252F08%252Fbalut.jpg%3Bhttp%253A%252F%252Fwww.bizarrefood.com%252Fblog%252Ffertilized-duck-embryo-balut%252F%3B295%3B300")

     visit root_path
     click_link link.short_url

     expect(page).to have_content("wikipedia")
end

这是我的模特:

class Link < ActiveRecord::Base
  before_create :shorten_url

  def self.sort_by_clicks
    order(clicks: :desc, created_at: :desc).all
  end

  def shorten_url
    self.short_url = (Figaro.env.base_url || "localhost:3000/") + SecureRandom.urlsafe_base64(6)
  end
end

问题是link.short_url没有将我想要的存根URL返回给我的数据库。我错过了什么?

1 个答案:

答案 0 :(得分:0)

如果您使用FactoryGirl,那么build(:link)只会创建新实例,但不会将其保存到数据库。

所以你应该,可能使用

link = create(:link, orig_url: "https://www.google.com/search?q=balut+egg&espv=2&biw=1280&bih=678&source=lnms&tbm=isch&sa=X&ei=CngVVanlMIG5ogSap4GQDQ&ved=0CAYQ_AUoAQ#imgdii=_&imgrc=qnYT21R-r5VDRM%253A%3BIbuD8fXhkqTEDM%3Bhttp%253A%252F%252Fwww.bizarrefood.com%252Fblog%252Fwp-content%252Fuploads%252F2012%252F08%252Fbalut.jpg%3Bhttp%253A%252F%252Fwww.bizarrefood.com%252Fblog%252Ffertilized-duck-embryo-balut%252F%3B295%3B300")

在测试中,强制回调触发器。

或者,从另一方面,您可以在Link模型中存根self.short_url方法。