Restricting VCR to specs - ruby-on-rails

Is there a way to make VCR active only when called via rspec in a Rails app? It works great for my tests, but I don't want it to intercept requests when outside of those tests.
I get Real HTTP connections are disabled if I use a client to connect to the my app and the app is calling an external web service.
Thanks,
Marc

make sure that your VCR gem is set in the proper group
# Gemfile
group :test do
......
gem 'vcr'
end
take a look at http://natashatherobot.com/vcr-gem-rails-rspec/ for more help.

I finally got this work as desired with Rails. I was able to disable VCR (WebMock, actually, which is the backend I chose for VCR) except when I'm running rspec. For background, I initially followed the instructions here when setting up VCR.
First, I create config/initializers/webmock.rb:
# Disable WebMock globally so it doesn't interfere with calls outside of the specs.
WebMock.disable!
Then I added the following around VCR.use_cassette() (in my case this is in spec_helper.rb:
config.around(:each, :vcr) do |example|
name = example.metadata[:full_description].split(/\s+/, 2).join("/").underscore.gsub(/[^\w\/]+/, "_")
options = example.metadata.slice(:record, :match_requests_on).except(:example_group)
+ # Only enable WebMock for the specs. Don't interfere with calls outside of this.
+ WebMock.enable!
VCR.use_cassette(name, options) { example.call }
+ WebMock.disable!
end
Hope that helps someone.

Related

How to stub download from remote url in Carrierwave

I have a User AR model and when I save a User instance with a populated value of remote_avatar_url, Carrierwave automatically downloads the avatar. More info about this feature here.
Now, in my tests, I want to stub this behavior. I know I can do:
allow_any_instance_of(UserAvatarUploader).to receive(:download!)
however, the rspec-mocks documentation discourages the use of allow/expect_any_instance_of.
What is the proper way of stubbing this specific feature of Carrierwave in tests?
P.S. I have already disabled image processing in tests:
config.enable_processing = false if Rails.env.test?
For me, the answer is to use the webmock gem. It blocks outbound HTTP connections during testing and allows you to easily stub responses.
After setting up the gem per the instructions, I added this to my tests:
body_file = File.open(File.expand_path('./spec/fixtures/attachments/sample.jpg'))
stub_request(:get, 'www.thedomainofmyimage.example.net').
to_return(body: body_file, status: 200)
Worked like a charm with CarrierWave's remote_<uploader>_url feature.

using VCR with Rspec in feature scenarios

I have a Rails 4 app that uses a custom authentication gem that authenticates users against a third-party API. The app requires authentication for most actions on the site (visitors can do very little).
I am trying to use VCR to record the api request made during authentication for all of the integration tests, but all examples that I can find on SO and the Relish documentation only cover how to do this with Rspec in a 'describe do' spec, as referenced here:
https://www.relishapp.com/vcr/vcr/v/1-6-0/docs/test-frameworks/usage-with-rspec
Since no customers are involved on this project, I am writing integration tests with Rspec and Capybara instead of Cucumber, so my tests are using the 'feature/scenario' format like so:
feature 'posts' do
scenario 'a user can log in' do
# use vcr for api request
sign_in_user # refers to a method that handles the api call to log in a user, which is what I would like VCR to record.
expect(page).to have_content("User signed in successfully")
end
end
Using the command described in the documentation:
use_vcr_cassette
inside of the 'scenario' block, returns an error:
Failure/Error: use_vcr_cassette
undefined local variable or method `use_vcr_cassette' for #<RSpec::ExampleGroups::Posts:0x007fb858369c38>
I followed the documentation to setup VCR in my spec/rails_helper.rb (which is included by the spec/spec_helper.rb)... which basically looks like this:
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'support/vcr_cassettes'
c.hook_into :webmock
end
Obviously added gem 'vcr' to my Gemfile development/test group and it is a thing in console and binding.pry from inside of a test.
Has anyone used VCR inside of a Rspec feature? or have any suggestions on what I might do as a workaround?
Thanks in advance
Solution: Taryn East got me to the solution, but it is slightly different than the link posted for anyone trying to do this moving forward.
here is the most basic config in spec/rails_helper.rb or spec/spec_helper.rb:
require 'vcr'
VCR.configure do |c|
c.cassette_library_dir = 'spec/cassettes'
c.hook_into :webmock
c.configure_rspec_metadata!
end
using c.configure_rspec_metadata! is required for Rspec to handle the :vcr tag.
And in an Rspec Feature spec:
feature 'users' do
scenario 'logged in users should be able to do stuff', :vcr do
# authenticate user or make other http request here
end
end
Oddly enough, in my tests - VCR is recording the response and if passes the first time, but fails the second time. I traced this to the response being stored differently than it is received.
On a normal request (using excon) like so:
resp = Excon.post(url, :body => data, :headers => { "Content-Type" => "application/x-www-form-urlencoded", "Authorization" => authorization_header })
The response has a header that is accessible in this format:
resp.headers["oauth_token"]
which returns an oauth token.
In the VCR response, it is being stored differently and only accessible as:
resp.headers["Oauth-Token"]
Which is weird, but workable. This may be a bug with VCR or some issue with Excon... too busy to figure that one out right now, but just a heads up in case anyone else uses this setup and gets a passing test with the live http request and a failing test when using the VCR cassette. A quick workaround is to either change the VCR cassette data to match what your code expects, or modify your code to accept either available value.

what to set in Capybara.app for a Middleman project?

In the env.rb to use Capybara you should setup Capybara.app = something
Middleman is based on sinatra so I was thinking to use Sinatra::Application but gives an error
Anyone know what should be put to set up Capybara in the proper way?
Although I've recently stated this answer in the (recently closed) GitHub issue that #bhollis gave, I should fill in the answer here as well in keeping with the spirit of StackOverflow.
In a spec_helper.rb file added to a spec folder in the root of your Middleman project, the assignment I've used is Capybara.app = Middleman::Application.server.inst - however, I configure it a little bit too like so:
Capybara.app = Middleman::Application.server.inst do
set :root, File.expand_path(File.join(File.dirname(__FILE__), '..'))
set :environment, :development
set :show_exceptions, false
end
A full example of this using RSpec can be found here.
The answer will eventually be at https://github.com/middleman/middleman/issues/895

Rails application settings and tests

In my app I've used SettingsLogic to handle the app's settings (such as facebook tokens etc.) which is a gem that basically parses the config/application.yml file and provides easy access to its content.
I've also used this configuration file to enable or disable i18n support for the entire app, as the app is more of a core app for many child apps.
And so in my routes.rb I do things like :
if Settings.i18n.enabled
match ':this', :to => 'that#place'
end
Or in models :
if Settings.i18n.enabled
scope :for_current_locale, lambda { where(:locale => I18n.locale) }
end
I'd like to test how the app responds to both states : when i18n is turned off and when it is turned on.
My problem is that the state is read from the configuration file when Rails initializes. So when I run my tests I could only run tests related to i18n.enabled being false, then change my configuration file and run tests related to i18n.enabled being true.
Is there some way I could reinitialize the app between 2 tests ? (I'm using Rspec)
Or should I automate some way of running 2 separate tests files for both i18n cases ?
Or maybe there is a better way ?
Thanks !
EDIT
As for the routes issue I managed to make the specs pass by changing my settings and reloading the routes explicitly :
before(:all) do
Settings.i18n["enabled"] = true
My::Application.reload_routes!
end
But still I feel this is not ideal, and what about things defined in models ? Can I reload my models as well before running specs ? Won't that duplicate stuff like callbacks ?
I think you simple can reconfigure your Application like following, for example in a rspec before_all block in your specific test file:
YourAppName::Application.configure do
config.i18n.enabled = true # or false
end
And in an after_all block you can set the configuration back to your default one.
I think that could work.

Fake call to a web service in all cucumber tests

My Rails app makes a call to a web service.
I am using the FakeWeb gem to fake these calls in some tests by registering the URI like this:
FakeWeb.register_uri(:get, "http://webservice.com/param?value=a", :response => fake_response)
How can I set this fake registration for the entire test environment, as opposed to setting it up manually for each test ?
Most likely, putting that in your spec/spec_helper.rb file will do the trick. I haven't used FakeWeb, myself, but that's where you'd put any global initialization.
Take look at VCR rubygem.
It records your test suite's HTTP interactions and replays them during test run.
In a file in spec/support/, make a call to register_uri inside a Before block:
Before do
FakeWeb.register_uri(:get, "http://webservice.com/param?value=a", :response => fake_response)
end
I use this trick to set up mock responses using webmock, and it works like a charm.

Resources