How to define request.domain in when testing

Hi,

My application relies on request.domain for doing its job. The problem I
am encountering, is that when running tests, request.domain returns
“test.host”, how can I change that so that it returns “mysite.com”?

Thanks in advance.

On 24.9.2008, at 12.51, Fernando P. wrote:

Hi,

My application relies on request.domain for doing its job. The
problem I
am encountering, is that when running tests, request.domain returns
“test.host”, how can I change that so that it returns “mysite.com”?

Set this somewhere in your test environment:

   ActionController::Base.default_url_options.update :host =>

mysite.com

//jarkko


Jarkko L.

http://www.railsecommerce.com
http://odesign.fi

Hi jarkko,

I get the following error message:

load_environment': undefined method default_url_options’ for
ActionController::Base:Class (NoMethodError)

From this
ticket:#22 default_url_options is being ignored by named route optimisation - Ruby on Rails - rails

It was at that time expected to deprecate default_url_options, so maybe
it was removed from Rails 2.1?

On 24.9.2008, at 14.07, Fernando P. wrote:

ticket:#22 default_url_options is being ignored by named route optimisation - Ruby on Rails - rails

It was at that time expected to deprecate default_url_options, so
maybe
it was removed from Rails 2.1?

Might be I’ve only played with it within action_mailer, where it still
works:
config.action_mailer.default_url_options = { :host =>
“development_url.com” }

Not sure if it works the same way with ActionController, though. You
can of course set the request host by hand in a setup method:

@request.host = host

//jarkko


Jarkko L.

http://www.railsecommerce.com
http://odesign.fi

Hi, I have one problem testing one method to learn rSpec. This is the
example

#foo.rb

class Foo < ActiveRecord::Base
has_one :bar

def foo
@bar.bar -= - 1
end
end

#bar.rb
class Bar < ActiveRecord::Base
end

#foo_spec.rb
require File.expand_path(File.dirname(FILE) + ‘/…/spec_helper’)

describe Foo do
before(:each) do
@bar = mock_model(Bar, :bar= => 1)
@foo = Foo.new(:bar => @bar)
@before_value = @foo.bar
end

it “should foo” do
@foo.foo.should be_equal(@value_before - 1)
end
end

I got this error:

Spec::Mocks::MockExpectationError in ‘Foo should foo’
Mock ‘Bar_1001’ received unexpected message :bar with (no args)
/home/carlos/NetBeansProjects/prueba/app/models/foo.rb:5:in `foo’
/home/carlos/NetBeansProjects/prueba/spec/models/foo_spec.rb:11:

How can I do this test using mocks?

Thanks ;).

On 24 Sep 2008, at 13:35, Carlos Rafael Belizón Ibáñez wrote:

end

end
How can I do this test using mocks?
try using stub_model instead of mock_model when you create @bar

If you create a mock object using mock_model(), or mock(), you have
to stub or mock absolutely all the interactions it will have with the
class under test. In this case, when you call Foo#foo, it calls the
#bar method on your mock Bar, which hasn’t been set up to expect that
call.

So either use stub_model(Bar), which will create an instance of your
concrete Bar class (and will therefore more likely know what to do
when #bar is called), or remember to call @bar.stub!(“bar-=”) or
whatever.

Make sense?

Thanks ;).


rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

cheers,
Matt

http://blog.mattwynne.net

In case you wondered: The opinions expressed in this email are my own
and do not necessarily reflect the views of any former, current or
future employers of mine.

On 24 Sep 2008, at 14:38, David C. wrote:

Or you could use mock_model(…).as_null_object (assuming you have the
current HEAD).

This is the new record / playback stuff eh?

cheers,
Matt

http://blog.mattwynne.net

In case you wondered: The opinions expressed in this email are my own
and do not necessarily reflect the views of any former, current or
future employers of mine.

On Wed, Sep 24, 2008 at 8:23 AM, Matt W. [email protected] wrote:

def foo
#foo_spec.rb
@foo.foo.should be_equal(@value_before - 1)
/home/carlos/NetBeansProjects/prueba/spec/models/foo_spec.rb:11:

How can I do this test using mocks?

try using stub_model instead of mock_model when you create @bar

If you create a mock object using mock_model(), or mock(), you have to stub
or mock absolutely all the interactions it will have with the class under
test.

Or you could use mock_model(…).as_null_object (assuming you have the
current HEAD).

On Wed, Sep 24, 2008 at 9:21 AM, Matt W. [email protected] wrote:

test.

Or you could use mock_model(…).as_null_object (assuming you have the
current HEAD).

This is the new record / playback stuff eh?

No relation. It’s just a method that lets you say
mock(‘foo’).as_null_object instead of mock(‘foo’, :null_object =>
true).

I’m really need your help guys to understand the philosophy of BDD. This
is a par of my Final Career Project.

Thanks ;).

El mié, 24-09-2008 a las 09:22 -0500, David C. escribió:

or mock absolutely all the interactions it will have with the class under


rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

Sorry, before I wrote with errors the example (it’s the problem if you
are remember without code at your face). This is the correct example
with the suggestions to fix the problem:

#foo.rb
class Foo < ActiveRecord::Base
has_one :bar

def foo
self.bar.count -= 1
end
end

#foo_spec.rb
require File.expand_path(File.dirname(FILE) + ‘/…/spec_helper’)

describe Foo do
before(:each) do
@bar = stub_model(Bar, :count => 1)
@foo = Foo.new(:bar => @bar)
@before_value = @foo.bar
end

it “should decrement bar.count in 1” do
@foo.foo
@foo.bar.count.should be_equal(@value_before - 1)
end
end

#bar.rb
class Bar < ActiveRecord::Base
end

And now, I got this error:
1)
NoMethodError in ‘Foo should decrement bar.count in 1’
undefined method count=' for #<Bar id: 1001, created_at: nil, updated_at: nil> /home/carlos/NetBeansProjects/RailsApplication1/app/models/foo.rb:5:in foo’
/home/carlos/NetBeansProjects/RailsApplication1/spec/models/foo_spec.rb:11:

What it’s wrong? Can I make this type of test with mock or stub?

On Wed, Sep 24, 2008 at 5:59 PM, Carlos Rafael Belizón Ibáñez
[email protected] wrote:

I’m really need your help guys to understand the philosophy of BDD. This
is a par of my Final Career Project.

Here’s a short tutorial to get you started.

http://blog.davidchelimsky.net/articles/2007/05/14/an-introduction-to-rspec-part-i

Let us know if you have any specific questions.

Cheers,
David

On 24 Sep 2008, at 16:02, Carlos Rafael Belizón Ibáñez wrote:

self.bar.count -= 1
@before_value = @foo.bar

end

What it’s wrong? Can I make this type of test with mock or stub?

You’re expecting the Bar class to implement an interface which
supports you calling count -= 1 on it.

Have you checked (for example, using script/console) that Bar does
indeed offer this method? The error indicates that it doesn’t, and
from the code you’ve shown us I’d be surprised if it did - it’s not
something you can do to normal ActiveRecord objects - you’d have to
destroy a particular instance, for example, for the result of count
to go down.

I think it might be easier for us if you can show us an example
that’s closer to what you’re actually trying to do.

cheers,
Matt

http://blog.mattwynne.net

In case you wondered: The opinions expressed in this email are my own
and do not necessarily reflect the views of any former, current or
future employers of mine.

On 25 Sep 2008, at 11:51, Carlos Rafael Belizón Ibáñez wrote:

/home/carlos/NetBeansProjects/ofs/app/models/alineado.rb:53:in
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

Have a look at this:

When you call foo -= 1, ruby does two things:

(1) asks foo for its value
(2) tells foo to have a new value, one less than the answer it got
back from the first question.

If you re-write more verbosely, you’ll see what I mean:

foo = foo - 1

Two operations are being done to foo. So if you want to mock out foo,
you have to mock out both those operations.

Make sense?

cheers,
Matt

http://blog.mattwynne.net

In case you wondered: The opinions expressed in this email are my own
and do not necessarily reflect the views of any former, current or
future employers of mine.

El jue, 25-09-2008 a las 10:27 +0100, Matt W. escribió:

I think it might be easier for us if you can show us an example
future employers of mine.


rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

Ok. I’m coding a web application called: SFO (Soccer Football Online).
This project it’s like game Football Manager, but all players are
humans. Now, I’m coding the Class Alineado, here’s the Model of this
Class:

== Schema Information

Schema version: 20080923152754

Table name: alineados

id :integer not null, primary key

club_id :integer not null

jugador_id :integer not null

partido_id :integer not null

posicion :integer not null

entrada :integer

salida :integer

alineado_id :integer

class Alineado < ActiveRecord::Base #This class would be Foo.
belongs_to :club
has_many :jugadores
belongs_to :partido
has_one :alineado
validates_presence_of :club_id, :jugador_id, :partido_id, :posicion

def jugando?
!entrada.nil? and entrada <= self.partido.minuto and salida.nil?
end

def sustituido?
!salida.nil? and salida <= self.partido.minuto
end

def banquillo?
entrada.nil? or sustituido? or !jugando?
end

def sustituido_por?
self.alineado
end

def cambiar_por(jugador_entrante) #This would be the method foo of Foo
class
cambio = false
if jugador_entrante.banquillo? && !jugador_entrante.sustituido? &&
jugador_entrante.club_id == self.club_id
if club_id == self.partido.local
if self.partido.cambios_local > 0
self.partido.cambios_local -= 1 #and this would be the
operation self.bar.count -= 1
cambio = true
end
else #el jugador es del equipo visitante
if self.partido.cambios_visitante > 0
self.partido.cambios_visitante -= 1 #same operation
cambio = true
end
end
end

if cambio
  self.salida = self.partido.minuto
  jugador_entrante.entrada = self.partido.minuto
end

cambio

end

def validate
errors.add(:entrada, “no debe ser menor que 0 si está jugando”) if !
entrada.nil? and entrada < 0
errors.add(:entrada, “no debe ser mayor que el minuto actual”) if !
entrada.nil? and self.entrada > self.partido.minuto
errors.add(:entrada, “no debe tener una entrada mayor o igual que la
salida al partido”) if !entrada.nil? and !salida.nil? and entrada >=
salida
errors.add(:salida, “no debe haber sustituido si no ha entrado al
partido”) if entrada.nil? and !salida.nil?
end
end

#partido.rb
Class Partido < ActiveRecord::Base #This would be the class Bar
end

#alineado_spec.rb
module AlineadoSpecHelper
def atributos_validos(partido=nil, jugador=1, club=1, posicion=1)
{
:club_id => club,
:jugador_id => jugador,
:partido => partido,
:posicion => posicion
}
end
end

describe Alineado, “.cambiar_por” do
include AlineadoSpecHelper

before(:each) do
@partido = mock(Partido)
@partido.stub!(‘local’).and_return(:equipo_local)
@partido.stub!(‘visitante’).and_return(:equipo_visitante)
@partido.stub!(‘minuto’).and_return(20)
end

describe “with the game in play and sustitutions aviable” do
before(:each) do
@partido.stub!(‘cambios_local’).and_return(3)
@partido.stub!(‘cambios_visitante’).and_return(3)
@jugador_sustituido = Alineado.new(atributos_validos(@partido,
:jugador_sustituido, :equipo_local))
@jugador_sustituido.entrada = 0
@jugador_entrante = Alineado.new(atributos_validos(@partido,
:jugador_entrante, :equipo_local))
@cambios_antes = @partido.cambios_local
end

it "should decrement in one the sustitutions aviables" do
  @jugador_sustituido.cambiar_por(@jugador_entrante)
  @partido.cambios_local.should eql(@cambios_antes - 1)
end

end

And I got this error:

Spec::Mocks::MockExpectationError in ‘Alineado.cambiar_por with the game
in play and sustitutions aviable should decrement in one the
sustitutions aviables’
Mock ‘Partido_1004’ received unexpected message :cambios_visitante= with
(2)
/home/carlos/NetBeansProjects/ofs/app/models/alineado.rb:53:in
`cambiar_por’
spec/models/alineado_spec.rb:263:
spec/models/alineado_spec.rb:193:

And I don’t know how fix this error. It’s possible test this?

P.D.: Sorry for my english.

El jue, 25-09-2008 a las 12:44 +0100, Matt W. escribió:

Matt


rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

Thanks. I’m understand what I must do to test this type specifications.
I changed my code and now it’s work fine, but I have one question:

What way it’s better to test this method? Using a real instance of game,
or using a mock?

Thanks ;).

On Thu, Sep 25, 2008 at 8:09 AM, Carlos Rafael Belizón Ibáñez
[email protected] wrote:

Matt


rspec-users mailing list
[email protected]
http://rubyforge.org/mailman/listinfo/rspec-users

Thanks. I’m understand what I must do to test this type specifications.
I changed my code and now it’s work fine, but I have one question:

What way it’s better to test this method? Using a real instance of game,
or using a mock?

It’s difficult to say which one is better without more context. There
are risks, costs and benefits to each approach and they are not the
same in every situation. But I can give you some things to think about
and evaluate given the rest of your code base and where you are in the
process of developing it.

If the game has a lot of associations and validation requirements, it
could be complicated to set up in the code example (costing you time)
and expensive to run (costing you more time every time you run the
suite). This suggests using a mock might serve you better in that
situation, but if you do so without any higher level integration
tests, then you introduce the risk of having all of your code examples
pass but the application falls apart because you changed something in
the real Game that didn’t reveal itself via the mock Game.

Also, and this is both very important and very subtle, tools like
rspec and processes like TDD and BDD aren’t only about artifacts (the
resulting code), but they are about process. For example, if you
choose to develop a Lineup object before the Game object is developed,
using a mock Game can help you stay focused on the Lineup and also
help you to discover what APIs and services the real Game will need to
support.

Using mock objects as part of your process encourages a smaller
surface area and, therefore, a higher level of decoupling between
objects. First, since you don’t have a real object at hand, you can
not access its internals. Second, since you’re developing the API for
the Game (in this example) from the perspective of the Lineup that
uses it, you’re pushed to thinking of the surface of the Game and the
relationship between consumer and supplier (you could say client and
server, but those terms are overloaded). Discovering APIs by exploring
interactions is a great way to improve the chances that you get usable
APIs.

When you do this the other way, working on the Game first and thinking
“gee, I wonder what services other objects might need … I’ll add
these 20 things …” you end up with some APIs that totally hit the
mark, some that just miss the mark, resulting in either re-work or,
worse, living with a less than ideal API. And you end up with some
APIs that are just never, ever used.

All of that said, you’re working in a situation in which you’ve
already developed the code and you are trying to backfill tests onto
it - the antithesis of TDD. So in this case you won’t get any of the
process and discovery benefits that you would had you developed things
test first. Which leaves you really deciding based on the risks of not
having your granular examples function as integration tests vs the
time it takes to run them.

That’s a lot, but I hope this is helpful.

Cheers,
David

Thanks to both. I think that is more powerful use mocks in my project to
explain to the tribunal the benefits of use mocks and stubs against real
instances to test the code.

Thanks a lot ;).

What way it’s better to test this method? Using a real instance of
game,
or using a mock?

It basically depends on how complex Game is. In this simplistic
example, there’s really no harm in testing both objects together at
the same time, but nine times out of ten in the real world, you want
to isolate your tests so that when a bug is introduced in Game it’s
only the specs for Game that fail, and not the specs for anything else.

Mocks help with this by putting ‘firewalls’ between the classes
you’re testing, so you can be sure that you’re only testing a single
class at once. Once you get the hang of them, they can also help you
to think a little more about the interactions between your classes,
and produce cleaner designs. The trade-off is that you need to keep
the mocked behaviour consistent with the actual behaviour of the
class being mocked.

It sounds as though you could benefit from reading about mocks. Check
out the links at the bottom of this page:
http://rspec.info/documentation/mocks/

cheers,
Matt

http://blog.mattwynne.net

In case you wondered: The opinions expressed in this email are my own
and do not necessarily reflect the views of any former, current or
future employers of mine.

Please open another thread to discuss your issue. This one is for
setting request.domain while doing tests.