The argument passed to Nokogiri is mocked and tested, so leave it.
FUGA_FUGA = ['Company', 'secret']
def hogegiri_method(fuga)
HOGE_COUNT = 5
HOGE_COUNT.times do |time|
html = Nokogiri::HTML(OpenURI.open_uri(url))
a, b, c =Regular expression messed up
break if FUGAFUGA.include?(a)
end
{ a: a, b: b, c: c }
end
It's a shit-like code because it's a code that can't be shown in various ways, but this time I want to create a fake return value as a mock.
html = Nokogiri::HTML(OpenURI.open_uri('secret'))
here
However, it is difficult to set the return value of Nokogiri directly with and_return.
--The return value is Nokogiri :: HTML :: Document, which does not return simple html. --The method is used inside the method, which can only be used for the return value peculiar to nokogiri.
Such
In other words, you have to let nokogiri do the work, but do not access the URL and get the desired data.
Then what to do
OpenUri.open_uri
Mock the return value of this and pass the value to be passed to the argument of Nokogiri.
It seems that the HTML you want to parse is included in the argument of Nokogiri. Then, in the production environment, you can copy the HTML of the URL you access and fetch, create an htmlfile, paste it there, and use it as the mock of the return value! !! I didn't write an article about how easy it was.
Final answer
spec/test.html
HTML copy
allow(OpenURI).to receive(:open_uri).and_return(File.new("#{Rails.root}/spec/test.html"))
Complete
Now the method works as if you were accessing the url and fetching it.
Furthermore, if you do the argument of ʻand_return like
nil, File.new ("# {Rails.root} /spec/test.html")` and you can not get the value as the logic of the method created this time, it is up to 5 Since it loops times, you can also confirm that it is looping.
Since I started the internship, I'm doing things that I would never do in personal development, so I'm going to get stuck every time, but I'm trying to get somehow taught and sticky
May have grown a little
Recommended Posts