lanej / zendesk2

Zendesk API V2 client using Cistern
http://lanej.io/zendesk2/
MIT License
25 stars 28 forks source link

2 instances of the same mock client #38

Closed betesh closed 9 years ago

betesh commented 9 years ago

In a Ruby-on-Rails controller test, I need to set up some data for my mock client. The actual controller builds a new Zendesk2::Client--it can't use the same instance as I used in the test to set things up, because if I inject the mock client into my application code, then I'm not really testing the application code.

However, when I try to create a new instance, I get this error:

~/.rvm/gems/ruby-2.2.2/gems/zendesk2-1.7.2/lib/zendesk2/client/request.rb:270:in `rescue in response': 
{:status=>422, :headers=>{"Content-Type"=>"application/json; charset=utf-8"}, 
:body=>{"error"=>"RecordInvalid", "description"=>"Record validation errors", 
"details"=>{"email"=>[{"description"=>"Email: me@example.com is already being used by another user"}]}}} (Zendesk2::Error)

From digging into the source code, it looks like the problem is that on this line, it assumes that whenever you instantiate a new Zendesk2::Client::Mock, you also want to instantiate a new user. In my case, that is an incorrect assumption.

Here's a minimal demo of the issue:

require "bundler/inline"
gemfile do
  gem "zendesk2"
end

require "zendesk2"

Zendesk2::Client.mock!
username = "ABC"
password = "DEF"
url = "https://abc.zendesk.com"
client1 = Zendesk2::Client.new(username: username, password: password, url: url)
client2 = Zendesk2::Client.new(username: username, password: password, url: url)

I'm assuming that in production mode (i.e. when not mocking), this won't be a problem--whenever you instantiate a Zendesk2::Client::Real, the user already exists, so I'm looking for a way to create the same experience using a Zendesk2::Client::Mock.

lanej commented 9 years ago

@betesh I think I understand what you're saying.

The referenced line attempts to seed the mock data with the user you initialized the client with. It falsely assumes that the client will only be initialized with those credentials once.

Seems like the solution would be to handle duplicates when seeding the mock data. Do you agree ?

betesh commented 9 years ago

Yes. i.e. before calling create_user, check whether the mock data for that client already contains a user with the same email.

lanej commented 9 years ago

@betesh https://rubygems.org/gems/zendesk2/versions/1.7.3 has the fix

betesh commented 9 years ago

Thanks!