在Rspec中测试创建变量赋值

时间:2012-10-30 05:55:48

标签: ruby-on-rails ruby-on-rails-3 testing rspec

我正在创建一个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

2 个答案:

答案 0 :(得分:1)

如果你想测试是否创建了微博,你必须将一些参数传递给post动作,在你的测试中你只构建一个新的Micropost(在内存中,没有保存),你的创建动作甚至都不知道它存在:

我应该这样做:

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

你应该测试重定向和flash消息(在需要时将save方法存根为true / false)

答案 1 :(得分:0)

您在micropost中获得了零值,因为您尚未在此行中发布任何数据:

post '/microposts'

您需要实际包含此数据:

post '/microposts', :micropost => p