Rspec surrounding shared_example with timecop - ruby-on-rails

I am trying to wrap Timecop around a shared_example spec i wrote
describe "timecop wrapping shared example" do
Timecop.freeze(1.day.ago) do
it_behaves_like "a shared example i would like to test using timecop"
end
end
shared_examples "a shared example i would like to test using timecop"
before :all do
puts "the current time is #{Time.now}"
end
... expect ...
end
but running this spec still uses the real time and not the frozen one
can Timecop work like this?
how else can i wrap large pieces of my test file but change the time it is running

Timecop needs to execute within an it or before block.
The following change will fix your problem.
describe "timecop wrapping shared example" do
before { Timecop.freeze(1.day.ago) }
it_behaves_like "a shared example i would like to test using timecop"
end
Rspec will reset the environment(including Timecop) after running each example.
A couple of tips I've found with time travel in tests that might be useful:
Timecop.travel is more reflective of how your code will work in real life as time never stays still. You can use it the same way as freeze, just swap out the freeze method for travel.
If you have Rails 4.1 or newer there are great time travel tools built in and you can drop your timecop gem. Here is a blog post and the docs if you want to learn more.

Related

Rails, Is there a way to generate Unit Tests from Existing Controllers and methods defined in them?

I was wondering if there is a script that can take existing codebase and generate unit tests for each method in controllers. By default all would be passing since they would be empty and i can remove tests i for methods i dont feel important.
This would save huge time and increase testing. Since i'd have to define only what each method should output and not boilerplate that needs to be written.
You really shouldn't be doing this. Creating pointless tests is technical debt that you don't want. Take some time, go through each controller and write a test (or preferably a few) for each method. You'll thank yourself in the long run.
You can then also use test coverage tools to see which bits still need testing.
You can use shared tests to avoid repetition. So for example with rspec, you could add the following to your spec_helper/rails_helper
def should_be_ok(action)
it "should respond with ok" do
get action.to_sym
expect(response).to be_success
end
end
Then in your controller_spec
describe UserController do
should_be_ok(:index)
should_be_ok(:new)
end

How do you test your Config/Initializer Scripts with Rspec in Rails?

So I was searching online for a solution, but there seems to be scarce information about testing initializers created in Rails.
At the moment, I've written a pretty large API call-n-store in my config/initializers/retrieve_users.rb file. It makes an API request, parses the JSON, and then stores the data as users. Being pretty substantial, I've yet to figure out the cleanest way to test it. Since I need to retrieve the users before any functions are run, I don't believe I can move this script anywhere else (although other suggestions would be welcomed). I have a couple questions about this:
Do I have to wrap this in a function/class to test my code?
Where would I put my spec file?
How would I format it RSpec-style?
Thanks!
I just gave this a shot and have passing rspec tests, I am going to further refactor my code and in the end it will be shorter, but here is a snapshot of what I did, using this link as a guide:
The gist of it is this: make a class in your initializer file with the functions you want, then write tests on the functions in the class.
config/initializers/stripe_event.rb
StripeEvent.configure do |events|
events.subscribe 'charge.dispute.created' do |event|
StripeEventsResponder.charge_dispute_created(event)
end
end
class StripeEventsResponder
def self.charge_dispute_created(event)
StripeMailer.admin_dispute_created(event.data.object).deliver
end
end
spec/config/initializers/stripe_events_spec.rb
require 'spec_helper'
describe StripeEventsResponder do
before { StripeMock.start }
after { StripeMock.stop }
after { ActionMailer::Base.deliveries.clear }
describe '#charge_dispute_created' do
it "sends one email" do
event = StripeMock.mock_webhook_event('charge.dispute.created')
StripeEventsResponder.charge_dispute_created(event)
expect(ActionMailer::Base.deliveries.count).to eq(1)
end
it "sends the email to the admin" do
event = StripeMock.mock_webhook_event('charge.dispute.created')
StripeEventsResponder.charge_dispute_created(event)
expect(ActionMailer::Base.deliveries.last.to).to eq(["admin#example.com"])
end
end
end
Seems like this would be tricky, since the initializers are invoked when loading the environment, which happens before the examples are run.
I think you've already figured out the most important step: move the code into another unit where it can be tested outside of the Rails initialization process. This could be a class or a module. Mock out the network dependencies using webmock.
Where should this code reside? See this (now quite ancient) answer by no less than Yehuda Katz himself. Put the spec file in the corresponding part of the tree; i.e. if the unit ends up in lib/my_class.rb, the spec goes in spec/lib/my_class_spec.rb. You may need to modify spec/rails_helper to load the spec file.

Ruby on Rails - RSpec Javascript Test with Capybara (new to RoR)

New to Ruby, Rails and TDD. I'm using RSpec with Capybara and Capybara webkit.
Trying to test if a div element exists on a page.
Test Code:
require 'spec_helper'
describe "Login module" do
before do
visit root_path
end
it "should have a module container with id mLogin" do
page.should have_css('div#mLogin')
end
it "should have a module container with id mLogin", :js => true do
page.evaluate_script('$("div#mLogin").attr("id")').should eq "mLogin"
end
end
The first test passes but the second test fails with:
Login module should have a module container with id mLogin
Failure/Error: page.evaluate_script('$("div#mLogin").attr("id")').should eq "mLogin"
expected: "mLogin"
got: nil
Ran the JS in browser dev tools and get "mLogin" rather than nil.
Any ideas? Thanks.
find('div#mLogin')[:id].should eq 'mLogin'
See this from doc:
#evaluate_script
Evaluate the given JavaScript and return the result. Be careful when using this with scripts that return complex objects, such as jQuery statements. execute_script might be a better alternative.
evaluate_script always return nil, as far as I remember.
Anyway, your second test seems like is testing if capybara works, because your first test is enough.
One likely problem is that the have_css matcher supports Capybara's synchronization feature. If the selector isn't found right away, it will wait and retry until it is found or a timeout elapses.
There's more documentation about this at http://rubydoc.info/github/jnicklas/capybara#Asynchronous_JavaScript__Ajax_and_friends_
On the other hand, evaluate_script runs immediately. Since this is the first thing you do after visiting the page, there's a race condition: it's possible that it executes this script before the page has finished loading.
You can fix this by trying to find an element on the page that won't appear until the page is loaded before you call evaluate_script.
Alternately, you can wrap your call in a call to synchronize to explicitly retry, but this is not generally recommended. For situations like this, you're much better off using Capybara's built-in matchers. The evaluate_script method should only be used as a last resort when there is no built-in way to accomplish what you need to do, and you need to take a lot of care to avoid race conditions.

Running rspec from rails application code

I've got a situation where I need to validate some regular expressions.
So, during my application run, I may want to test that a particular regex:
Contains no spaces
Contains only a certain number of capture groups
Does not use certain characters
Only contains a certain number of wildcards
rspec seems like the perfect tool for doing this. I realize that it's typically used to test application interfaces, assumptions and logic before an application is run, however. But, the natural syntax combined with the automatic reporting output would be nice to have.
Questions:
Is this an appropriate use of rspec?
How can one call a description from within a running application?
Or, should I abandon this approach and simply write methods within my class to perform the validations?
Using rspec in this way is highly discouraged and unusual. You should leave testing code in a :test group in your Gemfile and not reference it in your app.
Instead, use rails validations that your field matches a regex format, and then write tests in rspec to verify your validations.
This is definitely something new: using rspec inside rails for validation. But for specific problems one tends to propose to use a DSL, and as such rspec is a DSL which might just perfectly suited for your job.
So if that is the case: why not, yes, go ahead. Be creative and find new ways to use the tools you have.
Just a small warning: from the few points you marked, the complexity does not seem to be too big, so make sure you are not using a bazooka to kill a fly. Rspec is a big and very powerful tool, tying in rspec to run during the rails process might not be entirely straightforward.
If you want to generate a report, you could use the global after(:all) { puts "report goes here" } or after(:each). If you expect some of your data to blow up your tests, you can test for .should raise_exception. I imagine you'd be writing lots of exception handling to keep the expected failures out of the output. Logging the results to a database or a file might also be annoying. If you can, describe the test that you are doing on the data and then just parse the output of rspec at the end.
class Car
attr_accessor :doors
end
describe "Car" do
it "should have doors" do
Car.new.should respond_to(:doors)
fail("failing intentionally")
end
it "should pass this easily" do
Car.new should_not be nil
end
after(:all) { puts "report here" }
end
You can see below that I have a description of the test that failed.
$ rspec rspec_fail.rb
F.report here
Failures:
1) Car should have doors
Failure/Error: fail("failing intentionally")
RuntimeError:
failing intentionally
# ./rspec_fail.rb:9:in `block (2 levels) in <top (required)>'
Finished in 0.00052 seconds
2 examples, 1 failure
I would be easy enough to just make a report of the failures if this was testing text and regex's. Failure/Error: fail("Data has spaces") etc.

Should I write rails tests with the def or test keyword?

This seems like a simple question but I can't find the answer anywhere. I've noticed that in general, tests in a Ruby on Rails app can be written as:
test "the truth" do
assert true
end
or
def the_truth
assert true
end
It seems newer material writes tests the first way, but I can't seem to find a reason for this. Is one favored over the other? Is one more correct? Thanks.
There has been a shift in recent years from short, abbreviated test names to longer, sentence-like test names. This is partly due to the popularity of RSpec and the concept that tests are specs and should be descriptive.
If you prefer descriptive test names, I highly recommend going with the test method. I find it to be more readable.
test "should not be able to login with invalid password" do
#...
end
def_should_not_be_able_to_login_with_invalid_password
#...
end
Also, because the description is a string it can contain any characters. With def you are limited in which characters you can use.
I believe the first method was implemented starting with Rails 2.2.
As far as I am aware, it simply improves readability of your code (as def can be any function while test is used only in test cases).
Good luck!
As Mike Trpcic suggests you should check out RSpec and Cucumber. I'd like to add that you should also take a look at:
Shoulda (http://github.com/thoughtbot/shoulda/tree/master)
Factory Girl (http://github.com/thoughtbot/factory_girl/tree/master)
Shoulda is a macro framework for writing concise unit tests for your models/controllers, while the second is a replacement for fixtures.
I would suggest doing your testing with either RSpec or Cucumber. I use both to test all my applications. RSpec is used to test the models and controllers, and Cucumber tests the Views (via the included Webrat functionality).

Resources