0

我正在创建一个 rspec 测试,以查看 create 方法中的实例变量是否保留了构建的数据。但是,我的测试不起作用,因为我返回了这个错误......

Failure/Error: assigns[:micropost]should eq(@post)
expected: #<Micropost id: 1, content: "Hello there", user_id: 1>
got: #<Micropost id: 2, content: "Hello there", user_id: 1>

我的 rspec 测试是

describe ::MicropostsController do

before :each do
  @post = FactoryGirl.create(:micropost)
end

it "tests the instance variable in create method" do
    post :create, micropost: FactoryGirl.attributes_for(:micropost)
    assigns(:micropost).should eq(@post)
end

我的 FactoryGirl 文件是

FactoryGirl.define do

 factory :micropost do

  content "Hello there Bob!"
  user_id "1"
  #even if I got rid of the double quotations around 1, the stringify key error still 
  #pops up

 end

end

这是微柱控制器创建操作代码...

def create

@micropost = Micropost.new(params[:micropost])

 respond_to do |format|

  if @micropost.save

    format.html { redirect_to @micropost, notice: 'Micropost was successfully create.' 
    }

  else

    format.html { render action: "new" }

  end

 end

end
4

2 回答 2

1

如果您想测试创建了微博,您必须将一些参数传递给发布操作,在您的测试中,您只构建一个新的微博(在内存中,未保存)并且您的创建操作甚至不知道它存在:

我应该这样做:

before(:each) do
  @micro_mock = mock(:micropost)
  @micro_mock.stub!(:save => true)
end

it "creates a micropost" do
  params = {:micropost => {:something => 'value', :something2 => 'value2'}}
  Micropost.should_receive(:new).with(params).and_return(@micro_mock)
  post :create, params
end

it "assigns the created micropost to an instance variable" do
  Micropost.stub!(:new => @micro_mock)
  post :create
  assigns(:micropost).should == @micro_mock
end

您应该测试重定向和闪存消息(在需要时将保存方法存根为真/假)

于 2012-10-30T13:13:55.117 回答
0

你得到 nil 值是micropost因为你没有在这一行中发布任何数据:

post '/microposts'

您需要实际包含数据才能使其正常工作:

post '/microposts', :micropost => p
于 2012-10-30T06:12:30.057 回答