简体   繁体   中英

Mocking an incoming request in to rails

I am using FactoryGirl to mock my models for both unit (RSpec) tests and integration (Cucumber) tests. When creating a News factory I create a random image URL, which obviously doesn't exist within the project. When running a Selenium test this get's picked up as a 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

What's the best way to mock a response for my image?

You want to do the mock in the test that fetches that image, not in the factory.

Either that or just provide a static image file in the image link (you don't need to test that your model can accept different URL strings).

If you want to return 200, can you not just return it like this?

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

Just only added in your specs the following:

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

thanks webmock

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM