Ruby on rails RSpec模拟ActiveRecord的问题“首先查找到何处”

Ruby on rails RSpec模拟ActiveRecord的问题“首先查找到何处”,ruby-on-rails,ruby,ruby-on-rails-3,unit-testing,rspec,Ruby On Rails,Ruby,Ruby On Rails 3,Unit Testing,Rspec,我正试图为我的一个控制器整理我的RSpec测试,但它不起作用,我需要一些帮助来解决它 我的Rspec是: before(:each) do @topic = mock_model(Topic, :update_attributes => true) Topic.stub!(:where).with({:slug=>"some-slug"}).and_return(@topic) with_valid_user end it "should fin

我正试图为我的一个控制器整理我的RSpec测试,但它不起作用,我需要一些帮助来解决它

我的Rspec是:

  before(:each) do
    @topic = mock_model(Topic, :update_attributes => true)
    Topic.stub!(:where).with({:slug=>"some-slug"}).and_return(@topic)
    with_valid_user
  end

  it "should find topic and return object" do
    Topic.should_receive(:where).with("some-slug").and_return(@topic)
    put :update, :topic_slug => "some-slug", :topic => {}
  end
我尝试测试的控制器逻辑是:

  def get_topic
    @topic = Topic.where(:slug => params[:topic_slug]).first
    @topic
  end
但我得到的结果是:

 Failure/Error: Topic.stub!(:where).with({:slug=>"some-slug"}).first.and_return(@topic)
 NoMethodError:
   undefined method `first' for #<RSpec::Mocks::MessageExpectation:0x104c99910>
 # ./spec/controllers/topics_controller_spec.rb:41
关于本守则:

  def get_topic
    @topic = Topic.where(:slug => params[:topic_slug]).first
    @topic
  end
这些参数是不能更改的(至少不是很简单)。非常感谢您的进一步帮助

更改此行

Topic.should\u receive(:where.)。with(“some slug”)。and\u return(@Topic)

对此

Topic.should_receive(:where.)。with(“some slug”)。and_return([@Topic])

您需要数组,但返回一个元素。

更改此行

Topic.should\u receive(:where.)。with(“some slug”)。and\u return(@Topic)

对此

Topic.should_receive(:where.)。with(“some slug”)。and_return([@Topic])


您需要数组,但返回一个元素。

存根链是一种代码气味,应作为最后手段处理。它将您的规范与实现细节紧密地联系在一起,而实现细节可能会通过重构进行更改

我推荐如下:

Topic.should_receive(:with_slug).and_return(@topic)

然后在
主题
中添加一个
with_slug
方法,你就可以开始了。

存根链
是一种代码气味,应该作为最后的手段。它将您的规范与实现细节紧密地联系在一起,而实现细节可能会通过重构进行更改

我推荐如下:

Topic.should_receive(:with_slug).and_return(@topic)

然后在
Topic
中添加一个
with_slug
方法,你就可以开始了。

我做了你建议的更改,但现在我得到了:
Failure/Error:put:update,:Topic_slug=>“some slug”,:Topic=>{}Mock“Topic_1001”收到了意外消息:slug with(无参数)
-我认为这是因为行
@topic=topic.where(:slug=>params[:topic\u slug])。首先
。我做了你建议的更改,但现在我得到了:
失败/错误:put:update,:topic\u slug=>“some slug”,:topic=>{}Mock“topic\u 1001”收到了意外的消息:slug with(no args)
-我想是因为行
@topic=topic.where(:slug=>参数[:topic\u slug])。首先
。有没有办法解决这个问题?