How to rspec mock open-uri? - rspec-rails

I have this simple code where I am sending http request and reading all the response.
Here is my rails code
open("http://stackoverflow.com/questions/ask")
How can I write spec for this line of code. I dont have the option to use mocha and webmock. I can only use mocking framework of Rpsec.
I have tried to use this statement
OpenURI.stub!(:open_uri).should_receive(:open).with("http://stackoverflow.com/questions/ask")
but i keep getting this error
RSpec::Mocks::MockExpectationError: (#<RSpec::Mocks::MessageExpectation:0xd1a7914>).open("http://stackoverflow.com/questions/ask")
expected: 1 time
received: 0 times

I thought that the open method is defined on the level of the Kernel, but I was wrong.
If you would like to mock the open, you should do it on the level of your object like this:
it "should do something" do
object_under_test = ObjectUnderTest.new
object_under_test.should_receive(:open).with("http://example.org")
end

I did:
my_object.stub_chain(:open, :read) { "my return value" }

According to this link http://distillations.2rye.com/2011/08/mock-the-web-openuri/ the open function is defined on the Kernel module, but mixed into your controller. Therefore you need to stub the call at that level. This solution works well for RSpec controller tests:
html_content = <<-EOS
<html><head>
<title>Some Title</title>
</head>
<body>Some Content</body></html>
EOS
YourController.any_instance.stub(:open).and_return html_content

To stub open-uri you can use this syntax RSpec 3+
file = double('file')
expect(OpenURI).to receive(:open_uri).and_return(file)

Related

How can I use PHPUnit to make certain there are no debug print statements in the code?

In Symfony 4, I have an API function that returns a JSON response. It works, and all my tests pass. BUT, I had a print statement in the code, and so the React side of things wasn't happy with the extra print statement and blew an error.
So, I put in a test to make sure my function was returning valid json, expecting that the extra character would make that fail.
$content = $this->client->getResponse()->getContent();
$json = json_decode($content);
if (json_last_error() === JSON_ERROR_NONE) {
$content = $json;
}
Nope. Still passes. Is there any test I can do on the PHP side to make sure there are no random print statements left in the code?
You assert that your code isn't supposed to output anything:
$this->expectOutputString('');
Otherwise, a task like this might be more suited to a code sniffer that forbids debugging functions like var_dump, print_r, etc.

How to make symfony display exceptions in functional testing with phpunit

When I run unit tests with PhpUnit in console all exceptions are display immediately there. However when I moved to functional testing I cannot see exceptions which occur.
First I tried symfony WebTestCase as it was said here. So I called $client with needed parameters and I have a response. But it took time to me to understand that this behaviour is just like I manually open a page I want to test. And a response from $client->request contains text (html). Yes errors are show there but there are pretty much html and it is really hard to find the exception. Yes, I can use $crawler->filter('.text-exception')->first()->text() but I want so that exception was visible like in unit test. When I tested commands exceptions are shown by PhpUnit as well as normal.
I tried to copy code from web/app_dev.php to test case. But it is the same. I have only html response.
So how can I make it so that PhpUnit display exceptions in functional testing like in unit testing?
You can use profiler to do it:
$client->enableProfiler();
$client->request('GET', '/');
$profile = $client->getProfile();
$exceptionProfile = $profile->getCollector('exception');
if ($exceptionProfile->hasException()) {
$message = sprintf(
"No exception was expected but got '%s' with message '%s'. Trace:\n%s",
get_class($exceptionProfile->getException()),
$exceptionProfile->getMessage(),
$exceptionProfile->getException()->getTraceAsString()
);
throw new AssertionFailedError($message);
}

Unit tests in meteor can't find the code they need to test

I'm struggling with unit tests in Meteor. I want to use the velocity, jasmine package but I must be doing something wrong. The tests don"t seem to work because the test can't find the code to test. The test project is available on github.
The code that i want to test is here:
https://github.com/robvanpamel/coderepository/blob/master/meteor/sandwich-app/server/Services/SandwichService.js
The unit Test is here:
https://github.com/robvanpamel/coderepository/blob/master/meteor/sandwich-app/tests/jasmine/server/integration/spec/SandwichServiceSpec.js
When I uncomment the created SandwichService in the Unit Test, the test works, which is normal.
I haven't done any configuration elsewhere in meteor, and i think that is the problem. Do you have to put a package.js file where you specify your source code?
How can Jasmine know where it can find the SandwichService I'm trying to test? It is also the error i get.
"ReferenceError: SandwichesService is not defined "
EDIT
I was able to resolve it and updated the code repository in GitHub. The key was not to use the Javascript prototypes. so the below will not work
function SandwichesService(){};
SandwichesService.prototype.listSandwiches = function() {
// do stuff here
}
while the code below does work
SandwichService = {
listSandwiches: function(){
// do stuff here
}
};
I don't really understand why? Does somebody can tell me?
Kind regards and thanks upfront!
Rob
This is a Meteor issue not a testing issue :)
You need to put the SandwichesService on the global namespace. Your second block does that by default.
Try:
SandwichService = new SandwichesService()
(don't use var)

assertTextPresent equivalent in phpunit

I'm trying to test for the presence of a string somewhere in a long webpage. Using PHPUnit's assertRegExp if the string is not found it prints out the entire page and then finishes with matches PCRE pattern "/xxxxxx/". According to the documentation I should be able to specify a message a third that will be printed out if the test fails. That message is printed, followed by the full page source. What I'd like to do is just print the message. Using Selenium in my previous apps I used assertTextPresent and it would just print out confirmation that the text was/was not found, without filling my screen.
I have tried wrapping the assertRegExp in a try-catch but it didn't change anything.
You could try assertContains() instead of assertRegexp().
PHPUnit is responsible for printing out the failed text, and this differs from one assert method to another. It just might work.
If it does not, open an issue at PHPUnit's issue tracker about PHPUnit printing too much out.
I am using the getBodyText() method to get all page content and than I use assertTextPresent() to check the presence of pattern.
$this->assertTextPresent($this->getBodyText(), 'text to find');
The solution has been positivly tested with latest phpunit 4.7.
I use assertTrue(stripos($haystack, $needle) !== false, 'Failed assertion message');

Error while compiling botan sample example in Qt

I am trying to find out the error for two days but still haven't got this unknown reason figure out.
I have configured and compiled Botan library. Everything goes ok but when try to write this sample code to be run..
S2K* s2k = get_s2k("PBKDF2(SHA-256)");
s2k->set_iterations(4049);
SecureVector<byte> key_and_IV = s2k->derive_key(48, passphrase).bits_of();
SymmetricKey key(key_and_IV, 32);
it says error: 'class Botan::PBKDF' has no member named 'set_iterations'
How can I solve this problem ?
The Botan docs for v1.11.1 report that the function get_s2k() has been deprecated, recommending that you use get_pbkdf() instead.
According to the docs, get_sdk(algospec) just returns the result of a call to get_pbkdf(algo_spec) which will give you a pointer to an instance of the class Botan::PBKDF.
First things first then, your code needs to be something more like:
PBKDF *s2k = getpbkdf("PBKDF2(SHA-256)");
Unfortunately without knowing what you want to do with s2k I can't help any further, as the docs have no reference to a public member function of PBKDF called set_iterations(). You're getting the error you mention because Botan::PBKDF really does have no member named set_iterations. You need to read the docs, work out what the purpose of set_iterations() was in your now deprecated example and hence how to achieve that purpose in the newer version of the library.
Possibly you missed your library header... as your error message says: 'has no member named...'

Resources