title,body,link,tags,view_count,is_answered,score,answer_count
How to setup error 404 page in Ruby on Rails system testing,"<p>Rails 5.1 introduced <a href=""http://guides.rubyonrails.org/testing.html#implementing-a-system-test"" rel=""nofollow noreferrer"">system testing</a> that uses Capybara with Selenium to test the UI of Rails application.</p>

<p>I'm wondering to how to use this system testing to test the UI of error pages.</p>

<p>For standard controller tests, we can do something like below to assert response to be 404.</p>

<pre><code>test 'should get not_found' do
  get errors_not_found_url
  assert_response :not_found
end
</code></pre>

<p>But for system tests, if I go to a 404 page, exception will be thrown in controller level and tests terminate immediately without rendering the page.</p>

<pre><code>test '404 page should render with the correct title' do
  # act.
  visit NOT_FOUND_URL

  # assert.
  assert_equal(""#{APP_NAME} - #{TITLE_404}"", page.title)
end
</code></pre>

<p>Exception is thrown in controller level.</p>

<pre><code>$ rails test test/system/error/error_page_test.rb
Run options: --seed 30076

# Running:

Puma starting in single mode...
* Version 3.9.1 (ruby 2.3.1-p112), codename: Private Caller
* Min threads: 0, max threads: 1
* Environment: test
* Listening on tcp://0.0.0.0:55237
Use Ctrl-C to stop
2017-07-09 11:10:45 +1200: Rack app error handling request { GET /books/12345678 }
#&lt;ActionController::RoutingError: Could not find book '12345678' by id or name&gt;
/myapp/app/controllers/books_controller.rb:7:in `index'
/Users/yze14/.rvm/gems/ruby-2.3.1/gems/actionpack-5.1.2/lib/action_controller/metal/basic_implicit_render.rb:4:in `send_action'
/Users/yze14/.rvm/gems/ruby-2.3.1/gems/actionpack-5.1.2/lib/abstract_controller/base.rb:186:in `process_action'
...
</code></pre>

<p>Under development/test environment, <code>config.consider_all_requests_local</code> can be set to <code>false</code> in order to show error page instead of stracktrace. But this doesn't swallow exception during system tests.</p>
",https://stackoverflow.com/questions/44991652/how-to-setup-error-404-page-in-ruby-on-rails-system-testing,"['ruby-on-rails', 'ruby', 'selenium', 'capybara']",495,TRUE,0,1
I am having problems with my elif statements,"<p>I'm programming a game to try and improve my skills in python. In this part of the code I am trying to program a shop with a money system testing one variable against 5 different possible answers</p>

<pre><code>while True:
                choice=str(input(""What would you like to buy? (Type in 'nothing' when you don't want anymore items)  ""))
                if choice!=""health potion"" and ""strength potion"" and ""strength booster"" and ""armour piece"" and ""nothing"":
                    print()
                    next_line=input(""I do not understand what you wrote. Try again please "")
                    print()
                elif choice==""nothing"":
                    next_line=input(""The merchant says 'Thanks for business' "")
                    print()
                    break
                elif choice==""health potion"":
                    gold=gold-10
                    if gold&lt;0:
                        gold=gold+10
                        next_line=input(""Sorry but you don't have enough gold "")
                        print()
                    else:
                        next_line=input(""You bought a health potion "")
                        health_potions=health_potions+1
                        next_line=input(""You now have ""+str(gold)+"" gold coins "")
                        print()
                elif choice==""strength potion"":
                    gold=gold-15
                    if gold&lt;0:
                        gold=gold+15
                        next_line=input(""Sorry but you don't have enough gold "")
                        print()
                    else:
                        next_line=input(""You bought a strength potion "")
                        strength_potions=strength_potions+1
                        next_line=input(""You now have ""+str(gold)+"" gold coins "")
                        print()
                elif choice==""strength booster"":
                    gold=gold-45
                    if gold&lt;0:
                        gold=gold+45
                        next_line=input(""Sorry but you don't have enough gold "")
                        print()
                    else:
                        next_line=input(""You boosted your strength "")
                        strength_booster=strength_booster+1
                        next_line=input(""You now have ""+str(gold)+"" gold coins "")
                        print()
                elif choice==""armour piece"":
                    gold=gold-30
                    if gold&lt;0:
                        gold=gold+30
                        next_line=input(""Sorry but you don't have enough gold "")
                        print()
                    else:
                        next_line=input(""You bought an armour piece "")
                        armour=armour+1
                        next_line=input(""You now have ""+str(gold)+"" gold coins "")
                        print()
</code></pre>

<p>When you input <code>health potion</code> the code goes on like normal but with the other inputs it goes to this part of the code</p>

<pre><code>if choice!=""health potion"" and ""strength potion"" and ""strength booster"" and ""armour piece"" and ""nothing"":
                print()
                next_line=input(""I do not understand what you wrote. Try again please "")
                print()
</code></pre>
",https://stackoverflow.com/questions/44606749/i-am-having-problems-with-my-elif-statements,"['python', 'python-3.x']",76,TRUE,-3,2
Configuring WCF For Different Environments,"<p>What's the best practice in a desktop application for configuring WCF services to connect do different endpoints depending on whether your in a development environment, system testing environment, production, etc...?  When I did web application development connecting to DBs, I modified the web.config to have different connection strings based on vertical.  Is it the same approach with WCF endpoints and just update the app.config file?</p>

<p>Thanks!</p>
",https://stackoverflow.com/questions/42300948/configuring-wcf-for-different-environments,"['vb.net', 'visual-studio', 'wcf']",480,TRUE,0,1
"If you are ensuring a system is producing correct outputs based on inputs, what type of testing would you apply?","<p>If you are ensuring a system is producing correct outputs based on inputs, what type of testing would you apply?</p>

<p>For example, your business has a time sheet system. The only modifications you make to the system entails users must input their time on a daily basis, and that the system generated reports on a daily basis, rather than weekly?</p>

<p>Is it fair to say this would entail:</p>

<ul>
<li>System testing</li>
<li>Acceptance testing</li>
<li>(alternatively combined acceptance testing)</li>
</ul>

<p>Thoughts?</p>
",https://stackoverflow.com/questions/43381267/if-you-are-ensuring-a-system-is-producing-correct-outputs-based-on-inputs-what,"['testing', 'system', 'cat', 'uat']",14,FALSE,0,1
Rails 5.1 Configuring Built-in System Tests with RSpec,"<p>After watching a <a href=""https://www.youtube.com/watch?v=sSn4B8orX70"" rel=""noreferrer"">RailsConf video on ActionDispatch::systemTestCase</a>, I was excited to incorporate it into my current app.  Currently our test suite setup uses the following:</p>

<ul>
<li><a href=""https://rubygems.org/gems/rspec"" rel=""noreferrer"">rspec</a></li>
<li><a href=""https://rubygems.org/gems/factory_girl"" rel=""noreferrer"">factory_girl</a></li>
<li><a href=""https://rubygems.org/gems/capybara"" rel=""noreferrer"">capybara</a> <code># for feature specs</code></li>
<li><a href=""https://rubygems.org/gems/database_cleaner"" rel=""noreferrer"">database_cleaner</a> <code># for feature specs, mostly for testing js</code></li>
<li><a href=""https://rubygems.org/gems/selenium-webdriver"" rel=""noreferrer"">selenium-webdriver</a> <code># for feature specs</code></li>
<li><a href=""https://rubygems.org/gems/capybara&#39;"" rel=""noreferrer"">capybara-webkit</a> <code># for feature specs</code></li>
</ul>

<p>It was difficult to get the configuration working for our current setup, but we eventually got it working, thanks largely to an article by Avdi Grimm titled: <a href=""http://www.virtuouscode.com/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/"" rel=""noreferrer"">Configuring database_cleaner with Rails, RSpec, Capybara, and Selenium</a>.</p>

<p>My hope was to use the built-in system tests of rails released in rails <code>5.1</code>. Since rails now has system testing built in: all I would need to worry about configuring is the following:</p>

<ul>
<li><code>rspec</code></li>
<li><code>factory_girl</code></li>
</ul>

<p>And that is it because <code>ActionDispatch::systemTestCase</code> takes care of <code>capybara</code>, <code>database_cleaner</code>, and it is already configured for the <code>selenium</code> driver.</p>

<p>For example: currently my <code>feature specs</code> are written like so (Capybara within the context of RSpec):</p>

<pre><code>#spec/features/blogs/creating_blogs_spec.rb
require ""rails_helper""

RSpec.feature ""Logged in User can create a blog"" do
  before do
    create(:logged_in_user)
  end

  scenario ""successfully"", js: true do
    ...
  end
end 
</code></pre>

<p>So this is what a typical integration/feature/system spec might look like for a test suite configured with <code>rspec</code>, <code>database_cleaner</code>, <code>factory_girl</code>, and <code>capybara</code>.  I would like to convert it over to using <code>ActionDispatch::systemTestCase</code>.  </p>

<p>However: I would like to use <code>ActionDispatch::systemTestCase</code> within the context of <code>RSpec</code>.</p>

<p>The RailsConf video above shows how ActionDispatch::systemTestCase works within the context of rails' default test suite layout (ex: <a href=""https://rubygems.org/gems/minitest&#39;"" rel=""noreferrer"">minitest</a> with tests located in a <code>test</code> directory), but it did not discuss how to use ActionDispatch::systemTestCase within the context of RSpec.  </p>

<p>I could not find any resources on making rails' built-in system tests configurable with RSpec, including within the <a href=""http://edgeguides.rubyonrails.org/testing.html#system-testing"" rel=""noreferrer"">system testing section of the rails guides</a>.  Is this possible?</p>
",https://stackoverflow.com/questions/44269257/rails-5-1-configuring-built-in-system-tests-with-rspec,"['ruby-on-rails', 'ruby', 'rspec']",4159,TRUE,13,2
"Unit testing many simple method that call internal methods/other tested methods, resulting in complex (yet similar) output","<p>I've got data access layer that has two types of method <code>GetLatestX</code> and <code>GetX</code>. <code>GetLatestX</code> looks something like this:</p>

<pre><code>    public IElementType GetLatestElementType(Guid id)
    {
        IElementType record = null;
        using (DatabaseSession session = CreateSession())
        {
            record = session.Connection.Get&lt;ElementTypeRecord&gt;(id);
        }
        return record;
    }
</code></pre>

<p>That's reasonably easy to unit test.</p>

<p>However, <code>GetX</code> wraps this <code>GetLatest</code> in an RefCount Observable and emits new values in response to a messaging system. Testing this method is a lot more complex. I want to check the following, rather complex behavior:</p>

<ol>
<li>You can subscribe and a it retrieves a value from the database</li>
<li>It starts listening for messages</li>
<li>Subscribing again doesn't result in a repeated database call</li>
<li>When the mock message system simulates a message a new database access is called and the subscriptions get the new versions. Only one additional database call is used.</li>
<li>Unsubscribing the second subscription doesn't result in the system stopping listening to messages.</li>
<li>Unsubscribing to the first subscription results in disposal of resources, and unsubscription from the messages.</li>
</ol>

<p>So, I've got all this in a single unit test, which is hideous. However, I'm not sure how I could break it up. I could only test 1, but to test 2 I'd have to go through 1 and 2, for 3 I'd still have to go through steps 1, 2, 3 etc. So I'd just be copying the same giant test, but having Asserts in different places each time.</p>

<p>And the code I'm testing in this method:</p>

<pre><code>    public IObservable&lt;IElement&gt; GetElement(Guid id)
    {
        return CreateObservableFor(GetLatestElement(id), GetLatestElement);
    }
</code></pre>

<p>It's a single line, half of which has been tested earlier. The other half is private:</p>

<pre><code>    private IObservable&lt;T&gt; CreateObservableFor&lt;T&gt;(T entity, Func&lt;Guid, T&gt; getLatest)
    {
        Guid id = (entity as ConfigurationEntity).ID;

        //return subject;
        return Observable.Create&lt;T&gt;(observer =&gt;
        {
            // publish first value
            observer.OnNext(entity);

            // listen to internal or external update notifications from messages
            Action&lt;ConfigurationMessage&gt; callback = (message) =&gt;
            {
                // TODO, check time-stamp is after previous?

                // use callback to get latest value
                observer.OnNext(getLatest(id));
            };

            messageService.SubscribeToConfiguration(id.ToString(), callback);

            // if it has been completed and stop listening to messages
            return Disposable.Create(() =&gt;
            {
                Console.WriteLine(""Unsubscribing from topic "" + id);
                messageService.UnsubscribeToConfiguration(id.ToString(), callback);
            });
        }).Publish().RefCount();
    }
</code></pre>

<p>But it behaves the same way for all the <code>GetX</code> methods.</p>

<p>My first thought is I should split the <code>GetLatestX</code> into an interface I can test separately then mock - but that seems to split the data access class into two for no good reason other than unit tests. They don't really conceptually belong as separate units in my mind. Is there another way of 'mocking' this dependency within a class? Or should I just split them up for the sake of testing?</p>

<p>In the same vein, testing the functionality of GetX is effectively repeatedly testing the logic of <code>CreateObservableFor</code>. I see why I should be testing each API method rather than what is really the internals of the API (in case something changes), but it seems so... inefficient.</p>

<p>How can I structure this unit test in a better way?</p>

<p>Example test:</p>

<pre><code>    [Test]
    public void GetElementTypeTest()
    {
        // test data
        var id = Guid.NewGuid();
        var nameA = ""TestNameA"";
        var nameB = ""TestNameB"";

        // mock database
        var columnNames = new[] { ""ID"", ""Name"" };

        // data values A will be the first set of data returned, and after configuration update B will be returned
        var dataValuesA = new List&lt;object[]&gt;();
        dataValuesA.Add(new object[] { id, nameA });

        var dataValuesB = new List&lt;object[]&gt;();
        dataValuesB.Add(new object[] { id, nameB });

        mockDbProviderFactory = new MockDbProviderFactory()
            .AddDatareaderCommand(columnNames, dataValuesA)
            .AddDatareaderCommand(columnNames, dataValuesB);

        // test method
        IEMF emf = new EMF(mockMessageService.Object, new MockHistorian(), mockDbProviderFactory.Object, """");

        var resultObservable = emf.GetElementType(id);

        // check subscription to config changes has not occurred and database not accessed
        mockDbProviderFactory.Verify(f =&gt; f.CreateConnection(), Times.Once);
        mockMessageService.Verify(ms =&gt; ms.SubscribeToConfiguration(It.IsAny&lt;string&gt;(), It.IsAny&lt;Action&lt;ConfigurationMessage&gt;&gt;()), Times.Never);

        //subscribe to observable
        int sub1Count = 0;
        var subscription = resultObservable.Subscribe(result =&gt; {
            sub1Count++;

            // check result
            Assert.AreEqual(new ElementTypeRecord(id, (sub1Count == 1 ? nameA : nameB)), result, ""Result from EMF does not match data"");

        });


        // check subscribed to config changes and subscription called
        Assert.IsTrue(sub1Count == 1, ""Subscription not called"");
        mockMessageService.Verify(ms =&gt; ms.SubscribeToConfiguration(It.IsAny&lt;string&gt;(), It.IsAny&lt;Action&lt;ConfigurationMessage&gt;&gt;()), Times.Once);

        // check we've subscribed with our id
        Assert.AreEqual(this.configCallbacks[0].Item1, id.ToString(), ""Unexpected message system subscription topic"");

        // open a second, short term subscription and ensure that the system does not re-subscribe to updates, or read the data again
        int sub2Count = 0;
        resultObservable.Take(1).Subscribe(result =&gt; {
            sub2Count++;

            // check result (should be second data item)
            Assert.AreEqual(new ElementTypeRecord(id, nameB), result, ""Result from EMF does not match data"");
        });

        // check subscribed to config changes has not changed
        mockMessageService.Verify(ms =&gt; ms.SubscribeToConfiguration(It.IsAny&lt;string&gt;(), It.IsAny&lt;Action&lt;ConfigurationMessage&gt;&gt;()), Times.Once);

        //emit a new value by simulating a configuration change message
        this.configCallbacks[0].Item2(new ConfigurationMessage(DateTime.Now));

        // check subscriptions called
        Assert.IsTrue(sub1Count == 2, ""Subscription not called"");
        Assert.IsTrue(sub2Count == 1, ""Subscription not called"");

        // unsubscribe
        mockMessageService.Verify(ms =&gt; ms.UnsubscribeToConfiguration(It.IsAny&lt;string&gt;(), It.IsAny&lt;Action&lt;ConfigurationMessage&gt;&gt;()), Times.Never);
        subscription.Dispose();

        // verify subscription removed
        mockMessageService.Verify(ms =&gt; ms.UnsubscribeToConfiguration(It.IsAny&lt;string&gt;(), It.IsAny&lt;Action&lt;ConfigurationMessage&gt;&gt;()), Times.Once);
        Assert.IsTrue(this.configCallbacks.Count == 0, ""Unexpected message system unsubscription topic"");

        // validate that the connection, command and reader were used correctly
        mockDbProviderFactory.Verify(f =&gt; f.CreateConnection(), Times.Exactly(2));
        mockDbProviderFactory.MockConnection.Verify(c =&gt; c.Open(), Times.Exactly(2));
        mockDbProviderFactory.MockConnection.Verify(c =&gt; c.Close(), Times.Exactly(2));

        //first data call
        mockDbProviderFactory.MockCommands[0].Verify(c =&gt; c.PublicExecuteDbDataReader(It.IsAny&lt;CommandBehavior&gt;()), Times.Once);
        mockDbProviderFactory.MockCommands[0].MockDatareader.Verify(dr =&gt; dr.Read(), Times.Exactly(2));

        //second data call
        mockDbProviderFactory.MockCommands[1].Verify(c =&gt; c.PublicExecuteDbDataReader(It.IsAny&lt;CommandBehavior&gt;()), Times.Once);
        mockDbProviderFactory.MockCommands[1].MockDatareader.Verify(dr =&gt; dr.Read(), Times.Exactly(2));
    }
</code></pre>
",https://stackoverflow.com/questions/43275116/unit-testing-many-simple-method-that-call-internal-methods-other-tested-methods,"['c#', 'unit-testing', 'testing']",36,FALSE,1,0
Google Sign-in and Spring Security,"<p>I am ashamed to admit that I burned four full days trying to get Spring Security 3.1 to play nicely with Google Sign-in in a standard JSF web application. Both are awesome frameworks in their own right but they seemed incompatible. I finally got it to work in some fashion but strongly suspect that I have missed some fundamental concept and am not doing it the best way.</p>

<p>I am writing an app that our helpdesk uses to track system testing during maintenance activities when our systems are down and cannot host the app, so it is hosted externally. Our Active Directory and IdP are down during this activity so I cannot use our normal authentication systems. Google Sign-in is a perfect solution for this.</p>

<p>Google Sign-in works great in the browser using Google Javascript libraries and some simple code. The browser communicates with Google to determine if the user is already signed in, and if not, opens a separate window where the user can submit credentials and authenticate. Then a small bit of Javascript can send a concise, ephemeral id_token returned from Google to the server which the server can use to verify the authentication independently with Google. That part was easy. The beauty is that if the user is already signed into Gmail or some other Google app, authentication has already happened and Google does not challenge the user again. </p>

<p>Spring Security works great on the server side to protect specified resources and authenticate a user with a username and password. However, in this case, we never see the username or password - the credentials are protected by secure communication between the browser and Google. All we know is whether or not the user is authenticated. We can get the Google username, but Spring Security expects credentials that it can use to authenticate, to a database, in-memory user base, or any other system. It is not, to my knowledge, compatible with another system that simply provides yea-or-nay authentication in the browser.</p>

<p>I found many good examples online that use Spring Boot with EnableOAuth2Sso (e.g. <a href=""https://stackoverflow.com/questions/42727014/spring-boot-spring-security-spring-oauth2-google-sign-in"">here</a>) but surprisingly few that use Spring Security in a standard app server which does not support EnableOAuth2Sso, and those few did not show any solution I could discern.</p>

<p>Here is how I've done it. I followed Google's simple directions <a href=""https://developers.google.com/identity/sign-in/web/"" rel=""nofollow noreferrer"">here</a> to provide authentication in the browser. I added this code to the onSignIn() method to send the id_token to the server.</p>

<pre><code>var xhr = new XMLHttpRequest(); // Trigger an authentication for Spring security
        xhr.open(""POST"", ""/&lt;my app context&gt;/j_spring_security_check"", true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var params = ""profileID="" + profile.getId() + ""&amp;amp;fullname="" +  profile.getName() + ""&amp;amp;email="" + profile.getEmail() + ""&amp;amp;id_token="" + googleUser.getAuthResponse().id_token
            + ""&amp;amp;j_username="" + profile.getEmail() + ""&amp;amp;j_password="" + id_token;
        xhr.send(params);
        window.location.replace(""/&lt;my app context&gt;/index.xhtml"");
</code></pre>

<p>Unfortunately the Spring Authentication object, when passed to the AuthenticationProvider that I provided, did not contain anything but the j_username and j_password parameters as Authentication.getPrincipal() and Authentication.getCredentials(), but this is all I really needed. This is a bit of an abuse of those parameters since I have set them to email and id_token, not username and password.</p>

<p>I wanted to pass the user's full name and email, which Google provides in Javascript as googleUser.getName() and googleUser.getEmail(), to the backend as well. Since Spring Security does not accommodate anything but the username/password, and I was using Primefaces/JSF, I used Primefaces RemoteCommand to call a method on the backing bean with this information. This also feels a little clumsy.</p>

<p>In addition, I had to use window.location.replace() (in code above) because Spring Security did not redirect to my index.xhtml page as expected when I set this in the context with:</p>

<pre><code>&lt;security:form-login login-page='/login.xhtml' authentication-failure-url=""/login.xhtml?error=true"" default-target-url=""/index.html"" always-use-default-target=""true"" /&gt;
</code></pre>

<p>I have no idea why this does not work.</p>

<p>However, the app does now behave as I want in that it authenticates the user and the authenticated user can access the resources specified in Spring Security, and I wanted to share this in case anyone is doing a similar thing. Can anyone suggest a cleaner/better way? Thanks in advance.</p>
",https://stackoverflow.com/questions/46410516/google-sign-in-and-spring-security,"['authentication', 'jsf', 'spring-security', 'google-signin']",361,FALSE,0,0
