将传入的请求模拟到rails中

时间:2013-09-27 11:40:40

标签: ruby-on-rails testing routing mocking cucumber

我正在使用FactoryGirl来模拟我的模型,用于单元(RSpec)测试和集成(Cucumber)测试。在创建News工厂时,我创建了一个随机图片网址,这显然不存在于项目中。当运行Selenium测试时,这将被选为404。

FactoryGirl.define do
  factory :news do
    title { Faker::Lorem.sentence }
    image { Faker::Internet.relative_url ".jpg" }
    body { Faker::Lorem.paragraphs.join "\r\n\r\n" }

    before :create do
      Timecop.freeze Faker::Date.time
    end

    after :create do
      Timecop.return
    end

    after :build do |article|
      # Somehow mock a 200 response for #{article.image}
    end

    factory :published_news do
      published true
    end
  end
end

模拟我的图片响应的最佳方法是什么?

3 个答案:

答案 0 :(得分:0)

你想在获取该图像的测试中进行模拟,而不是在工厂中。

或者只是在图像链接中提供静态图像文件(您不需要测试模型是否可以接受不同的URL字符串)。

答案 1 :(得分:0)

如果你想返回200,你能不能像这样返回它?

after :build do |article|
 ["200", "OK"]
end

答案 2 :(得分:0)

只是在您的规格中添加了以下内容:

describe Zomg do
  it 'should get ok' do 
    stub_request(:any, "http://factory-generated-url-here/").to_return(body: '', status: 200)

   # you stuff with request        
  end   
end

感谢webmock