Rails 3 - 模拟/存根 - 测试控制器

发布于 2024-12-10 12:31:11 字数 307 浏览 0 评论 0原文

我有一个关于测试以下 Rails 代码行的问题:

https://gist.github.com/1289849

在我的测试代码中我有这样的东西(显然不起作用):

https://gist.github.com/1289848

有人可以帮我为此编写正确的测试代码吗?

谢谢

i have a question about testing following line of Rails code:

https://gist.github.com/1289849

in my test code i have something like this(obviously don't works):

https://gist.github.com/1289848

Someone can help me write right test code for this ?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

記柔刀 2024-12-17 12:31:11

为了使测试更容易,您应该将此逻辑移至客户端模型上的类方法。我还假设您的用户模型上有一个 has_many :clients ,这就是您的查询所暗示的内容。

类似于:

class Client
  def self.search_by_name(name)
    all.where("name LIKE %?%", name).order("name ASC")
  end
end

然后在您的控制器中:

@clients = current_user.clients.search_by_name(params[:search])

这将允许您在单元测试中进行测试,而不是在集成测试中进行测试。

client_spec.rb:

describe Client, 'searching by name' do
  let(:current_user) { User.create!(...) }
  let!(:client) { Client.create!(:name => 'client name', :user => current_user) }

  it 'should find the clients by name' do
    Client.search_by_name('client name').should include(client)
  end
end

那么您的集成测试只需存根 search_by_name 方法并返回一组模拟,从而更容易测试。

To make testing it easier, you should move this logic to a class method on your Client model. I'm also assuming you have a has_many :clients on your user model, which is what your query is implying.

Something like:

class Client
  def self.search_by_name(name)
    all.where("name LIKE %?%", name).order("name ASC")
  end
end

Then in your controller:

@clients = current_user.clients.search_by_name(params[:search])

This will allow you to test in a unit test, rather than with an integration test.

client_spec.rb:

describe Client, 'searching by name' do
  let(:current_user) { User.create!(...) }
  let!(:client) { Client.create!(:name => 'client name', :user => current_user) }

  it 'should find the clients by name' do
    Client.search_by_name('client name').should include(client)
  end
end

Then your integration test could just stub the search_by_name method and return a collection of mocks, making it easier to test.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文