Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor rspec tests #17

Merged
merged 1 commit into from
Oct 15, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ vagrant up
### OS X

1. [Install Xcode](https://developer.apple.com/xcode/downloads/)
2. [Install Vagrant](http://docs.vagrantup.com/v2/installation/) (**1.7.2 or later**)
2. [Install Vagrant](http://docs.vagrantup.com/v2/installation/) (**1.7.4 or later**)
3. [Install Virtualbox](https://www.virtualbox.org/wiki/Downloads)
4. Clone this repo
5. Do the installation in terminal:
Expand All @@ -71,7 +71,7 @@ $ vagrant up
To use virtualbox make sure you have ```vt-x``` enabled in your bios.
You might need to disable ```hyper-v``` in order to use virtualbox.

1. [Install Vagrant](http://docs.vagrantup.com/v2/installation/) (**1.7.2 or later**)
1. [Install Vagrant](http://docs.vagrantup.com/v2/installation/) (**1.7.4 or later**)
2. [Install Virtualbox](https://www.virtualbox.org/wiki/Downloads)
3. Clone this repo
4. Do the installation in terminal:
Expand Down Expand Up @@ -132,6 +132,12 @@ Vagrant box has xdebug pre-configured for you. If you want to investigate certai
3. Click update button


## Testing

### Rspec
This repo contains basic rspec testing for wordpress
See the file ```tests/rspec/test.rb``` as an example.

## Development strategies

The layout of this repo is designed in a way which allows you to open source your site without exposing any confidential data. By default all sensitive data is ignored by git.
Expand Down
66 changes: 66 additions & 0 deletions tests/rspec/lib/config.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
require 'capybara/poltergeist'
require 'rspec'
require 'rspec/retry'
require 'capybara/rspec'

# Load our default RSPEC MATCHERS
require_relative 'matchers.rb'
require_relative 'wp.rb'

##
# Create new user for the tests (or automatically use one from ENVs: WP_TEST_USER && WP_TEST_USER_PASS)
##
WP.createUser

RSpec.configure do |config|
config.include Capybara::DSL
config.verbose_retry = true
config.default_retry_count = 1
end

Capybara.configure do |config|
config.javascript_driver = :poltergeist
config.default_driver = :poltergeist # Tests can be more faster with rack::test.
end

Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app,
debug: false,
js_errors: true, # Use true if you are really careful about your site
phantomjs_logger: '/dev/null',
timeout: 60,
:phantomjs_options => [
'--webdriver-logfile=/dev/null',
'--load-images=no',
'--debug=no',
'--ignore-ssl-errors=yes',
'--ssl-protocol=TLSv1'
],
window_size: [1920,1080]
)
end


RSpec.configure do |config|

##
# After the tests put user into lesser mode so that it's harmless
# This way tests won't increase the index of user IDs everytime
##
config.after(:suite) {
puts "\ndoing the cleanup..."
WP.lowerTestUserPrivileges
}

##
# Make request more verbose for the logs so that we can differentiate real requests and bot
# Also in production we need to pass shadow cookie to route the requests to right container
##
config.after(:each) {
page.driver.add_header("User-Agent", "wp-palvelu-testbot")
#if this is a shadow route the request into right shadow
if WP.shadow?
page.driver.set_cookie("wpp_shadow", WP.shadowHash, {:path => '/', :domain => WP.host})
end
}
end
2 changes: 1 addition & 1 deletion tests/rspec/lib/matchers.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#Include these into your rspec for basic testing
# Include these into your rspec for basic testing

RSpec::Matchers::define :have_title do |text|
match do |page|
Expand Down
163 changes: 163 additions & 0 deletions tests/rspec/lib/wp.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
require 'uri'
require 'ostruct'

# Check if command exists
def command?(name)
`which #{name}`
$?.success?
end

##
# Module to make tests integrate with WordPress and wp-cli
##
module WP
# Use this test user for the tests
# This is populated in bottom
@@user = nil

# Return siteurl
# This works for subdirectory installations as well
def self.siteurl(additional_path="/")
if @@uri.port && ![443,80].include?(@@uri.port)
return "#{@@uri.scheme}://#{@@uri.host}:#{@@uri.port}#{@@uri.path}#{additional_path}"
else
return "#{@@uri.scheme}://#{@@uri.host}#{@@uri.path}#{additional_path}"
end
end

# sugar for @siteurl
def self.url(path="/")
self.siteurl(path)
end

#sugar for @siteurl
def self.home()
self.siteurl('/')
end

# Return hostname
def self.hostname
@@uri.host.downcase
end

# sugar for @hostname
def self.host
self.hostname
end

# Check if this is shadow
def self.shadow?
if @@shadow_hash.empty?
return false
else
return true
end
end

# Return ID of shadow container
def self.shadowHash
@@shadow_hash
end

# Return OpenStruct @@user
# User has attributes:
# { :username, :password, :firstname, :lastname }
def self.getUser
if @@user
return @@user
else
return nil
end
end

# sugar for @getUser
def self.user
self.getUser
end

# Checks if user exists
def self.user?
( self.getUser != nil )
end

# These functions are used for creating custom user for tests
def self.createUser
if @@user
return @@user
end

# We can create tests which check the user name too
firstname = ENV['WP_TEST_USER_FIRSTNAME'] || 'Test'
lastname = ENV['WP_TEST_USER_LASTNAME'] || 'WP-Palvelu'

if ENV['WP_TEST_USER'] and ENV['WP_TEST_USER_PASS']
username = ENV['WP_TEST_USER']
password = ENV['WP_TEST_USER_PASS']
elsif command? 'wp'
username = "testbotuser"
password = rand(36**32).to_s(36)
system "wp user create #{username} #{username}@#{@@uri.host} --user_pass=#{password} --role=administrator --first_name=#{firstname} --last_name=#{lastname} > /dev/null 2>&1"
unless $?.success?
system "wp user update #{username} --user_pass=#{password} --role=administrator > /dev/null 2>&1"
end
# If we couldn't create user just skip the last test
unless $?.success?
return nil
end
end

@@user = OpenStruct.new({ :username => username, :password => password, :firstname => firstname, :lastname => lastname })
return @@user
end

# Set smaller privileges for the test user after tests
# This is so that we don't have to create multiple users in production
def self.lowerTestUserPrivileges
unless @@user
return false
end

# Use the same user multiple times without changing it if was from ENV
if ENV['WP_TEST_USER']
return true
end

system "wp user update #{@@user.username} --role=subscriber > /dev/null 2>&1"
return true
end

private
##
# Check site uri before each call
# Use ENV WP_TEST_URL if possible
# otherwise try with wp cli
# otherwise use localhost
##
def self.getUri
if ENV['WP_TEST_URL']
target_url = ENV['WP_TEST_URL']
elsif command? 'wp' and `wp core is-installed`
target_url = `wp option get home`.strip
else
puts "WARNING: Can't find configured site. Using 'http://localhost' instead."
target_url = "http://localhost"
end

URI(target_url)
end

# Parse shadow hash from container id
def self.getShadowHash
if ENV['CONTAINER']
return ENV['CONTAINER'].partition('_').last
else
return ""
end
end

# Cache the parsed site uri here for other functions to use
@@uri = getUri()

# Check for container id as well
@@shadow_hash = getShadowHash()
end
Loading